React的文档(https://reactjs.org/docs/hooks-reference.html#usestate)有这个例子:
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>
</>
);
}为什么前面的代码比以下代码更好:
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>
</>
);
}发布于 2019-12-22 06:57:10
不是的。在你的例子中,另一种方式是完全可以的。然而,还有其他情况,即
(a)如果您具有设置状态的效果:
useEffect(() => {
// ... do stuff
setCount(count + 1);
}, [count]); // whoops, thats kind of recursion. However if we omit it, count might change in the meantime(b)如果执行异步操作,并且state局部变量可能不保存当前状态值:
(async function action() {
await /*something*/;
setCount(count + 1); // is count still up to date?
})();在这些情况下,使用setState回调是解决问题的一种方法。
https://stackoverflow.com/questions/59440442
复制相似问题