Why is setState in reactjs Async instead of Sync?

后端 未结 7 1369
一生所求
一生所求 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:18

    You can call a function after the state value has updated:

    this.setState({foo: 'bar'}, () => { 
        // Do something here. 
    });
    

    Also, if you have lots of states to update at once, group them all within the same setState:

    Instead of:

    this.setState({foo: "one"}, () => {
        this.setState({bar: "two"});
    });
    

    Just do this:

    this.setState({
        foo: "one",
        bar: "two"
    });
    

提交回复
热议问题