1、State 的更新可能是异步的
setState 使用注意事项
1.1、异步原因:
每次更新数据,视图要实时更新, 出于性能考虑,React 可能会把多个 setState() 调⽤用合并成一个调⽤。
1.2、异步情况:
setState 在合成事件(方法)中是异步的
setState在生命周期函数中是异步的
1.3、同步情况:
setState 在原生事件中是同步的
setState 在setTimeout是同步的
1.4、拿到最新的state数据方法:
1、handle放在setState 回调函数中;
2、用setTimeout 包裹存在setState的handle;
1.5、State 的更新会被合并
changeValue = v => {
this.setState({
counter: this.state.counter + v
});
};
setCounter = () => {
this.changeValue(1); // 会被合并调
this.changeValue(2); // 只会执行该行
};
1.6、串行使用setState: 链式调用更新
changeValue = v => {
this.setState(
state => ({ counter: state.counter + v })
);
};
setCounter = () => {
this.changeValue(1);
this.changeValue(2);
};