简体   繁体   中英

Is this.setState() of react.js synchronous or asynchronous?

Please look into the following code. I have tried calling setState one below the other. It looks like count which is returned from the second call of setState is always set to this.state.count . Here, It's always assigned with 3

    class Counter extends React.Component {
    constructor(props){
        super(props);
        this.handleReset = this.handleReset.bind(this);
        this.state = {
            count : 0
        };
    }

    handleReset() {
        this.setState(() => {
            return {
                count: 1
            }
        });
        this.setState(() => {
            return {
                count: 3
            }
        });
    }
    render() {
        return (
            <div> 
                <h1>Count:{this.state.count}</h1>
                <button onClick={this.handleReset}>reset</button>
            </div>
        );
    }
  }
  ReactDOM.render(<Counter />, document.getElementById('app'));

According to React docs, it can be async.

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state

(original source, and correct code example)

setState is asynchronous. You can pass callback as second argument and see the updated state.

this.setState({ count: 5 }, () => {
  console.log(this.state.count) // 5
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM