Why is setState in reactjs Async instead of Sync?

后端 未结 7 1384
一生所求
一生所求 2020-11-21 22:58

I have just found that in react this.setState() function in any component is asynchronous or is called after the completion of the function that it was called i

7条回答
  •  情深已故
    2020-11-21 23:26

    Yes, setState() is asynchronous.

    From the link: https://reactjs.org/docs/react-component.html#setstate

    • React does not guarantee that the state changes are applied immediately.
    • setState() does not always immediately update the component.
    • Think of setState() as a request rather than an immediate command to update the component.

    Because they think
    From the link: https://github.com/facebook/react/issues/11527#issuecomment-360199710

    ... we agree that setState() re-rendering synchronously would be inefficient in many cases

    Asynchronous setState() makes life very difficult for those getting started and even experienced unfortunately:
    - unexpected rendering issues: delayed rendering or no rendering (based on program logic)
    - passing parameters is a big deal
    among other issues.

    Below example helped:

    // call doMyTask1 - here we set state
    // then after state is updated...
    //     call to doMyTask2 to proceed further in program
    
    constructor(props) {
        // ..
    
        // This binding is necessary to make `this` work in the callback
        this.doMyTask1 = this.doMyTask1.bind(this);
        this.doMyTask2 = this.doMyTask2.bind(this);
    }
    
    function doMyTask1(myparam1) {
        // ..
    
        this.setState(
            {
                mystate1: 'myvalue1',
                mystate2: 'myvalue2'
                // ...
            },    
            () => {
                this.doMyTask2(myparam1); 
            }
        );
    }
    
    function doMyTask2(myparam2) {
        // ..
    }
    

    Hope that helps.

提交回复
热议问题