gpt4 book ai didi

reactjs - 正确使用useState

转载 作者:行者123 更新时间:2023-12-03 13:43:41 25 4
gpt4 key购买 nike

我看到有些人使用这样的钩子(Hook)更新状态:

const [count, setCount] = useState(0)

方式一:setCount(count + 1)

方式2:setCount(count => count + 1)

这两种方式有什么区别?

最佳答案

来自文档:

State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

因此,当根据当前状态的值更新状态时,最好使用回调版本。

const [count, setCount] = useState(0); // initial state is 0

如果你例如像在单个处理程序中一样多次更新状态:

setCount(count + 1); 
// new state will be 1

setCount(count + 1);
// new state will still be 1 because updates are async
// and `count` still is 0 at the time of calling this

鉴于

setCount(count => count + 1); 
// new state will be 1

setCount(count => count + 1);
// new state will be 2 because the value passed
// to the callback will include the previous update

如果您想安全,请在根据当前状态进行更新时始终使用回调。

更多信息可以在docs中找到.

关于reactjs - 正确使用useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57458349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com