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

标签 javascript reactjs react-hooks

考虑简单的状态钩子(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/

相关文章:

rxjs - 如何将 useReducer 和 rxjs 与 React hooks 一起使用?

javascript - 在 PHP while 循环中随机化 jquery 中 "DIV"的边框颜色

javascript - setTimeout 之后的 setInterval

android - React Native ellipsizeMode - 2 个文本在同一行

javascript - node_modules/@types/react/index"' 没有默认导出

javascript - 如何禁止 ESLint 将项目添加到 useEffect 的观察者数组中?

javascript - Chart.js 的新扩展语法是什么?

JavaScript -Change CSS color for 5 seconds - 如何添加缓动效果?

reactjs - 如何在reactjs中不使用getFieldDecorator的情况下验证ant design formitems?

javascript - 将输入数据添加到深层对象React.JS