React - useState - why setTimeout function does not have latest state value?

前端 未结 2 628
悲&欢浪女
悲&欢浪女 2020-12-10 02:17

Recently I was working on React Hooks and got stuck with one problem/doubt?

Below is a basic implementation to reproduce the issue, Here I\'m just toggling fla

2条回答
  •  长情又很酷
    2020-12-10 03:13

    This boils down to how closures work in JavaScript. The function given to setTimeout will get the flag variable from the initial render, since flag is not mutated.

    You could instead give a function as argument to toggleFlag. This function will get the correct flag value as argument, and what is returned from this function is what will replace the state.

    Example

    const { useState } = React;
    
    function App() {
      const [flag, toggleFlag] = useState(false);
    
      const _onClick = () => {
        toggleFlag(!flag);
    
        setTimeout(() => {
          toggleFlag(flag => !flag)
        }, 2000);
      };
    
      return (
        
    ); } ReactDOM.render(, document.getElementById("root"));
    
    
    
    

提交回复
热议问题