Why is setState in reactjs Async instead of Sync?

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

    Good article here https://github.com/vasanthk/react-bits/blob/master/patterns/27.passing-function-to-setState.md

    // assuming this.state.count === 0
    this.setState({count: this.state.count + 1});
    this.setState({count: this.state.count + 1});
    this.setState({count: this.state.count + 1});
    // this.state.count === 1, not 3
    
    Solution
    this.setState((prevState, props) => ({
      count: prevState.count + props.increment
    }));
    

    or pass callback this.setState ({.....},callback)

    https://medium.com/javascript-scene/setstate-gate-abc10a9b2d82 https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b

提交回复
热议问题