I have read in this official article these lines:
this.propsandthis.statemay be updated asynchronously, you should not rely on their values for calculating the next state.
Can anyone please explain to me what the following code is trying to achieve by giving an example.
this.setState((prevState, props) => ({
couter: prevState.counter + props.increment
}));
They say you should do like that instead of the below example.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
They can't assure the state will have the correct value if you access like this because setState() will happen asynchronously, other updates could occur and change the value. If you are going to calculate the state based on the previous state, you have to make sure you have the last and most up to date value, so they made setState() accept a function that is called with prevState and props, so you can have the correct value to update your state, like the example below.
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
To add to Bruno's answer, the correct function above is called a pure function. React is big on something called immutability which means that every declared value should never be changed from its original declaration if possible. The variables in that function aren't your actual props and state until you pass them in, which means on the javascript function stack (the thread that queues up sync and async calls) the values and references to properties will be stored differently, creating uncertainty of what the value will be in the "wrong" case.
来源:https://stackoverflow.com/questions/50837670/reactjs-setstate-previous-state-is-the-first-argument-props-as-the-second-argum