
为什么会这样?
第一次渲染时,状态变量count初始化为0。
组件安装后,useEffect()调用 setInterval(log, 2000)计时器函数,该计时器函数计划每 2 秒调用一次log()函数。 在这里,闭包log()捕获到count变量为0。
之后,即使在单击Increase按钮时count增加,计时器函数每 2 秒调用一次的log(),使用count的值仍然是0。log()成为一个过时的闭包。
解决方案是让useEffect()知道闭包log()依赖于count,并在count改变时正确处理间隔的重置。
function WatchCount() {
const [count, setCount] = useState(0);
useEffect(function() {
const id = setInterval(function log() {
console.log(`Count is: ${count}`);
}, 2000);
return function() {
clearInterval(id);
}
}, [count]);
return (
<div>
{count}
<button onClick={() => setCount(count + 1) }>
Increase
</button>
</div>
);
}
正确设置依赖项后,一旦count发生变化,useEffect()就会更新闭包。
3.2 useState()
<DelayedCount>组件有 1 个button ,以 1 秒延迟异步增加计数器。
function DelayedCount() {
const [count, setCount] = useState(0);
function handleClickAsync() {
setTimeout(function delay() {
setCount(count + 1);
}, 1000);
}
return (
<div> {count} <button onClick={handleClickAsync}>Increase async</button> </div>
);
}
现在打开演示(codesandbox。 快速单击 2 次按钮。 计数器仅更新为1,而不是预期的2。
每次单击setTimeout(delay, 1000)将在 1 秒后执行delay()。delay()此时捕获到的 count 为 0。
两个delay()都将状态更新为相同的值:setCount(count + 1) = setCount(0 + 1) = setCount(1)。
这是因为第二次单击的delay()闭包中已捕获了过时的count变量为0。
为了解决这个问题,我们使用函数式方法 setCount(count => count + 1)来更新count状态。
function DelayedCount() {
const [count, setCount] = useState(0);
function handleClickAsync() {
setTimeout(function delay() {
setCount(count => count + 1); }, 1000);
}
function handleClickSync() {
setCount(count + 1);
}
return (
<div>
{count}
<button onClick={handleClickAsync}>Increase async</button>
<button onClick={handleClickSync}>Increase sync</button>
</div>
);
}
打开演示(codesandbox。 再次快速单击按钮2次。 计数器显示正确的值2。
当一个返回基于前一个状态的新状态的回调函数被提供给状态更新函数时,React 确保将最新的状态值作为该回调函数的参数提供。
setCount(alwaysActualStateValue => newStateValue);
这就是为什么在状态更新过程中出现的过时装饰问题可以通过函数这种方式来解决。
4.总结
当闭包捕获过时的变量时,就会发生过时的闭包问题。
解决过时闭包的有效方法是正确设置 React 钩子的依赖项。或者,在失效状态的情况下,使用函数方式更新状态。
好了,以上就是这一次的分享,希望大家能收获一定的经验,避免以后在 Hooks 的使用中出现上面提到的这些问题。