react setState 的坑
问题
setState 是更新 state 的 API,进而会引发组件的重新渲染。然而在使用过程中发现有些坑(参见 react 正确使用状态):
1. setState(obj)一般情况下不会立即更新 state 的值;
2. 同一 cycle 的多次 setState 调用可能会合并(性能考虑)
对于第一点,引用下边的例子:
1
2
3
4
5
function incrementMultiple() {
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
}
代码运行时,虽然是对 state 加了三次,但是每次加操作都是针对初始的 state,所以最终相当于仅加了一次。即上述代码等同于下边的代码:
1
2
3
4
5
6
Object.assign(
previousState,
{quantity: state.quantity + 1},
{quantity: state.quantity + 1},
...
)
为什么
从 react 生命周期看 setState 生效时间
要理解其原因,我们要先