为什么在 React 中使用闭包值会变得陈旧?

Why would a value get stale using closure in React?

the documentation for useEffect() 中显示了以下示例:

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
}

然后说:

Experienced JavaScript developers might notice that the function passed to useEffect is going to be different on every render. This is intentional. In fact, this is what lets us read the count value from inside the effect without worrying about it getting stale. Every time we re-render, we schedule a different effect, replacing the previous one.

我不明白为什么 count 会在 useEffect() 中变得陈旧,因为 useEffect 在它的闭包中有 count。由于 useEffect() 是一个钩子,它不应该总是可以访问最新的状态变量吗?另外,一般来说,我如何才能确保我始终拥有状态变量的最新值?

I don't understand why count would get stale inside useEffect() since useEffect has count within its closure.

请记住,Example 将被多次调用,每次渲染一次。所以有 N 个渲染器、N 个 count 变量和 N 个 useEffect 函数。因此,确实每个效果函数在其闭包内都有 count,但每个效果函数在其闭包内都有一个 specific count。无论在创建闭包时它有什么价值,这就是它在效果 运行s 时将具有的价值。如果您只创建函数一次,关闭 count 的第一个值,那么该代码将只会看到 count 的第一个值(即 0)。

Also, in general, how can I be sure that I always have the latest value for a state variable?

如果您正在设置状态,那么您始终可以使用 setState 函数版本访问最新值。例如:

setCount(prev => /* calculate new state from prev */)`

对于其他情况,要么将状态包含在 useEffect 的依赖数组中,以便在计数更改时效果 re-runs:

useEffect(() => {
  // some code that uses `count`
}, [count]);

或者,如果您希望在每次渲染时都达到 运行 效果,则完全关闭依赖项数组。

useEffect(() => {
  // some code that uses `count`
});