gpt4 book ai didi

javascript - 我可以依靠 useState 值来计算新状态吗?

转载 作者:行者123 更新时间:2023-12-03 07:25:21 26 4
gpt4 key购买 nike

考虑简单的状态钩子(Hook):

const [count, setCount] = React.useState(0);

我想增加或减少计数。基本上做 hooks docs 中所示的相同操作.

但作为一个已知的 fact对于旧 this.setState功能:

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



根据旧状态更新状态的正确方法是:
this.setState((state) => ({
counter: state.counter + 1
}));

是否同样适用于 setCount ?
或者我可以确定 count总是最新的?

最佳答案

useState Hook 的工作方式与 this.setState 不同.调用您的二传手,setCount在下面的示例中,确实异步工作,但由于 count在渲染功能组件期间不会更改,评估是确定性的。
以下示例逐字复制 Hooks at a Glance在 React 文档中,它是 100% 安全的(在未安装的组件上调用方法不会有任何错误),并且会按预期运行:

function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
唯一需要使用功能更新的时候,您将函数传递给 setCount是如果您需要调用 setCount引用状态时多次。请注意,这不是因为 setState是异步的——这是因为 count在下一次渲染之前不会更新。
例如, 这将是一个问题 :
<button
onClick={() => {
setCount(count + 1)
setCount(count + 1) // since `count` is not dynamically updated mid-render, this evaluates to the same value as above
}}
/>
在实践中,这种模式比较少见。您不会以这种方式在单个函数中多次调用 setter。相反,如果您将 setter 作为子项的 prop 传递,并且这些子项引用由 setter 控制的状态,那么您将使用功能更新模式。但是,即使在这种情况下, React will re-render the component with each successive value .
至于这是否是一种可靠和/或推荐的方法的担忧,React 文档对此有这样的说法( source):

You might hear a recommendation to always write code like setCount(c => c + 1) if the state you’re setting is calculated from the previous state. There is no harm in it, but it is also not always necessary.

In most cases, there is no difference between these two approaches. React always makes sure that for intentional user actions, like clicks, the count state variable would be updated before the next click. This means there is no risk of a click handler seeing a “stale” count at the beginning of the event handler.

However, if you do multiple updates within the same event, updaters can be helpful. They’re also helpful if accessing the state variable itself is inconvenient (you might run into this when optimizing re-renders).

If you prefer consistency over slightly more verbose syntax, it’s reasonable to always write an updater if the state you’re setting is calculated from the previous state. If it’s calculated from the previous state of some other state variable, you might want to combine them into one object and use a reducer.

关于javascript - 我可以依靠 useState 值来计算新状态吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59827925/

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