2017-10-26

聚沙

State Updates May Be Asynchronous

1
2
3
4
// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

仍然是错误的:

1
2
3
4
5
6
7
// Wrong
const { counter } = this.state;
const { increment } = this.props;

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

正确的用法:

1
2
3
4
// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

Comments