掌握React的稳定值

The concept of stable value is a distinctly React term, and especially relevant since the introduction of Functional Components. It refers to values (usually coming from a hook) that have the same value across multiple renders. And they’re immediately confusing (as you can see in the gist below), so in this post we’ll walk through some cases where they really matter and how to make sense of them.

稳定值的概念是一个明显的React术语,特别是在引入功能组件之后。它指的是在多次渲染中具有相同价值的值(通常来自一个钩子)。它们会让人感到困惑(正如你在下面的要点中看到的那样),所以在这篇文章中,我们将介绍一些它们真正重要的情况,以及如何理解它们。

  1. useState and useReducer return a state update function that is constant – the hook will always return the same function. The value is guaranteed to be stable, because we know that the same object will be returned until we call the state update function.
  2. useStateuseReducer 返回一个恒定的状态更新函数 - 钩子将总是返回同一个函数。这个被保证是稳定的,因为我们知道在我们调用状态更新函数之前会返回同一个对象。
  3. useRef returns an object that is guaranteed to be constant. You can change the ref.current value without triggering a re-render.
  4. useRef 返回一个保证是恒定的对象。你可以改变ref.current 值,而不触发重新渲染。
  5. Creating an array literal seems innocent enough…but this is unstable! A new array instance will be created on every render. This is fine from a performance standpoint (unless you’re inserting millions of items in the array), but if you pass the array to a function that expects a stable value… there be dragons!
  6. 创建一个数组的字面意思似乎很简单......但这是不稳定的每次渲染时都会创建一个新的数组实例。从性能的角度来看,这是好的(除非你在数组中插入数百万个项目),但是如果你把数组传递给一个期望有稳定值的函数......那就有龙了!"。
  7. Similarly for anonymous functions and object literals. It’s obvious once you see it, but many React developers are surprised when a rendering issue can be tracked down to an anonymous function being passed to an onPress prop.
  8. 对于匿名函数和对象字面也是如此。一旦你看到这一点就很明显了,但是当一个渲染问题被追踪到一个匿名函数被传递到一个onPress prop时,许多React开发者都会感到惊讶。
  9. To create a stable value, useCallback and useMemo are your friends.
  10. 为了创造一个稳定的价值,useCallbackuseMemo 是你的朋友。

From this example we can come up with a definition of stability in React: “stability” is the conditions which will result in a change to a value. A va...

开通本站会员,查看完整译文。

Home - Wiki
Copyright © 2011-2024 iteam. Current version is 2.129.0. UTC+08:00, 2024-07-04 14:55
浙ICP备14020137号-1 $Map of visitor$