闭包和 useState 钩子

closures and useState hook

我有点难以理解 React Hooks 和闭包,我找不到简单的答案来回答我的问题。

这是一个代码片段Codesandbox

    function WatchCount() {
      const [count, setCount] = useState(0);

       return (
         <div>
           {count}
           <button
             onClick={() => {
               setCount(count + 1);
               setCount(count + 1);
             }}
            >
             Increase
           </button>
        </div>
       );
   }

我不明白的是,如何使我调用 setCount 两次,两次加 1 并单击一次显示 2

更新是批量和异步的。当调用状态 setter 时,React 将使用新值对状态的更新进行排队。所以,调用:

setCount(count + 1);

很快就会告诉 React re-render WatchCountcount + 1.

两次调用 setCount(count + 1); 没有任何作用,因为这两次,你都在告诉 React 设置相同的新状态——例如,如果 count 从 0 开始,两次调用都会导致setCount(1).

(请记住,count 变量是使用 const 声明的 - 直到下一个渲染周期再次调用该函数时,它的值才会更改)

如果你出于某种原因想用两个单独的语句向 count 添加两个,你可以这样做的一种方法是使用 回调形式 ,它将 React 的当前状态值作为参数:

setCount(count => count + 1);
setCount(count => count + 1);

这将导致第一个 setCount 递增状态,然后新状态作为参数传递给 second setCount,所以它会再次增加。