首页 > 解决方案 > 使用 useState 钩子时计数器不增加

问题描述

我有以下代码:

  const [count1, setCount1] = useState(0);


  const handleAsyncUpdate = async () => {
    setCount1(count1 + 2);
    setCount1(count1 + 1);
  };

  const handleSyncUpdate = () => {
    setCount1(count1 + 2);
    setCount1(count1 + 1);
  };

  console.log("render", count1);
  return (
    <div className="App">
      <h2>{count1}</h2>
      <button type="button" onClick={handleAsyncUpdate}>
        Click for async update
      </button>
      <button type="button" onClick={handleSyncUpdate}>
        Click for sync update
      </button>
    </div>
  );
}

当我单击第二个按钮时,我希望<h2>{count1}</h2>渲染3(0 + 1 + 2),但它会渲染1.

如果我切换setCount1(count1 + 1);setCount1(count => count + 1);那么它可以正常工作,但是为什么呢?

标签: reactjsreact-hooks

解决方案


我认为您对工作方式useState(或者即使this.setState您正在使用类)感到困惑。这些操作总是异步的,React 根据它认为的优先级来安排这些更改。

通过放置async一个函数,您并不是说它突然异步,而是说它返回一个Promise.

就 React 的工作方式而言,这并没有改变任何东西。如此有效地你handleSyncUpdatehandleAsyncUpdateReact 基本相同,它们都触发异步操作(改变状态)。

setCount1(count => count + 1)- 使用这个,你实际上是在使用最后一个状态值来更新,保证新值将是最后一个 + 1。

setCount1(count1 + 1)- 在这种情况下,您使用的值在调用它的那一刻和 React 执行更新的那setState一刻之间被另一个值改变。setState

我希望这有帮助


推荐阅读