【问题标题】:React useState Batch updateReact useState 批量更新
【发布时间】:2021-05-04 12:25:20
【问题描述】:
import "./styles.css";
import {useState} from 'react';

export default function App() {

  const [count, setCount] = useState(0);
  const [count2, setCount2] = useState(0);

  console.log("Render: ", count, count2);

  function update() {
    setCount(count + 1);
    setCount(count + 1);
  }

  function updateWithCB() {
    setCount2(prevCount => prevCount + 1);
    setCount2(prevCount => prevCount + 1);
  }

  return (
    <div className="App">
      <p>{count}</p>
      <button onClick={update}>+</button>
      <br />
      <p>{count2}</p>
      <button onClick={updateWithCB}>+ with CB</button>
    </div>
  );
}

我是一个学习反应,遇到了这种行为。单击 + 时,它只更新一次,但单击 + with cb 时,它会按预期更新两次。这是否意味着 useState 函数调用被合并,如果是这样,当多个 useState 调用正在使用时如何预测合并?为什么在单击 + 按钮一次时它不打印 2 呢?任何反应的具体原因? 谢谢

【问题讨论】:

  • updateWithCB 中,您正在添加上一个计数,因此一旦第一个函数setCount2(prevCount =&gt; prevCount + 1); 运行计数已更新,因此您第二次运行prevCount 中的计数值为1,因此它更新为2. 但是在update() 函数中 prevCount 没有被跟踪,因此它给出了 1。
  • 欲了解更多信息,请查看stackoverflow.com/a/54807520/11727479

标签: reactjs react-hooks


【解决方案1】:

由于 setState 批处理,在这种情况下(在更新函数中),之前的 setState 将被最后一个 setState 覆盖,因此您需要使用在 updateWithCB 中使用的函数 setState。

看看这个答案,我认为它很清楚:What is prevState in ReactJS?

【讨论】:

    【解决方案2】:

    基本上,这就是你的update 函数内部发生的事情: setCount(0 + 1); setCount(0 + 1);

    所以,最后你将count 设置为1。但是,当您使用回调方式时,它会按预期工作:状态更新异步,所有回调都传递实际状态值。(在您的情况下为prevCount)。

    【讨论】:

      猜你喜欢
      • 2020-12-22
      • 2021-03-03
      • 2021-11-15
      • 2020-11-15
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 2021-01-07
      相关资源
      最近更新 更多