【发布时间】:2020-01-09 16:58:05
【问题描述】:
我正在阅读 React Hook documentation 关于功能更新的内容,请参阅以下引文:
“+”和“-”按钮使用函数形式,因为更新 值基于之前的值
但我看不出需要功能更新的目的以及它们与直接使用旧状态计算新状态之间的区别。
为什么 React useState Hook 的更新函数需要函数式更新形式? 有哪些例子可以清楚地看到差异(所以使用直接更新会导致错误)?
例如,如果我从文档中更改此示例
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
</>
);
}
直接更新count:
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={() => setCount(count - 1)}>-</button>
</>
);
}
我看不到任何行为差异,也无法想象计数不会更新(或不是最新的)的情况。因为每当计数发生变化时,都会调用 onClick 的新闭包,捕获最新的 count。
【问题讨论】:
标签: reactjs react-hooks