高级前端
react
【Q368】关于 React hooks 的 caputre value,以下输出多少

关于 React hooks 的 caputre value,以下输出多少

更多描述

function App() {
  const [count, setCount] = useState(0);
  const incr = () => {
    setTimeout(() => {
      setCount(count + 1);
    }, 3000);
  };
  return <h1 onClick={incr}>{count}</h1>;
}

当连续点击 10 次时,会输出多少

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 373 (opens in a new tab)

Author 回答者: zckpp (opens in a new tab)

应该是1吧,在state被update之前count一直还是0

Author 回答者: jkLennon (opens in a new tab)

连续点击 10 次是在3s内完成,那传给setTimeout的count都为0,输出应该都是1

Author 回答者: cloudXA (opens in a new tab)

验证一下 https://codesandbox.io/s/sharp-dawn-5e5hp?file=/src/capture.js (opens in a new tab)