Article From:https://segmentfault.com/q/1010000011117535
Question:

reactThere is a paragraph in the official website receiving that states and props are updated asynchronously, so don’t calculate the value of the next state based on them and give an error example:

this.setState({
  counter: this.state.counter + this.props.increment,
});

My understanding here is that props is the data passed by the parent component ~ his update is done in the function in the parent component, and the data in the state is updated in the current component ~ but no matter how these two objects are updated ~ is set in the right way (that is, to use the setS in the current group.Tate or the parent component uses setState to update the data.) these update operations should trigger react to re render the component. It should be correct, no matter how the data is asynchronously changed, and why the official web will have this description

Answer 0:

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
It’s the official explanation.
setStateIt can be batched to improve its performance, and the updates to this. props and this. state are asynchronous and cannot rely on the previous state to calculate the value of the next state.
For instance:
At first this.state.counter=1;
Execute once
this.setState({
counter: this.state.counter + 1,
});
And then in the execution
this.setState({
counter: this.state.counter + 1,
});
The expected result should be the this.state.counter value of 3, but this.state.counter may not be 3.

Answer 1:

Consider calling two times setState in a function.

// ...
this.setState({
    counter:this.state.counter+1
})
// some code
this.setState({
    counter:this.state.counter+2
})

The final result of this code may be that couter has increased by only 2 becausethis.state.counterNot always from the lateststate
The way to avoid it is to use the function as a functionsetStateParameters

this.setState((prevState, props) => {
  return {counter: prevState.counter + props.step};
});

This is also the method recommended by the official network

In addition, the code snippet of your title is not found in the official website. If you can, please trouble it.

Leave a Reply

Your email address will not be published. Required fields are marked *