Strange behavior of React hooks: delayed data update

前端 未结 3 651
走了就别回头了
走了就别回头了 2020-12-10 18:42

Strange behavior: I expect that the first and the second console.log display a different result, but they display the same result and the value is changed only on the next c

3条回答
  •  孤城傲影
    2020-12-10 18:59

    The setState hook doesn't update the value in the component directly. It updates it's internal state, causes a rerender of the component, and then returns the new state value, which you assign to count.

    When you console.log(count) inside test, you display the current value of count, which is the old value (before the update). If you'll move the console.log() to the render, you'll see the new value:

    const { useState } = React;
    
    const Component = () => {
      const [count, setCount] = useState(false);
    
      const test = () => {
        console.log('before: ', count);
        setCount(!count)
      }
      
      console.log('after: ', count);
    
      return (
        
    ); } ReactDOM.render( , demo );
    
    
    
    

提交回复
热议问题