React实例对象中setState方法获取最新状态
遇到的问题
使用setState后发现state中的数据没有改变,还是上一次的数据
state = {
count: 0,
};
handleAddNumber = () => {
const { count } = this.state;
this.setState({ count: count + 1 });
console.log(this.state.count); // 0
};
使用setState后无法获取最新状态的原因
官方解释:
setState() 将对组件 state 的更改排入队列,并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件。将 setState() 视为请求而不是立即更新组件的命令。为了更好的感知性能,React 会延迟调用它,然后通过一次传递更新多个组件。React 并不会保证 state 的变更会立即生效。setState() 并不总是立即更新组件。它会批量推迟更新。这使得在调用 setState() 后立即读取 this.state 成为了隐患。
个人理解:
在某些情况下(在react控制的生命周期钩子和react事件监听回调函数中),通过setState()方法修改实例状态是一个异步的过程,异步任务将在其他任务队列执行完毕后才会执行,因此执行setState方法后打印出的数据不是最新的。
解决方法
setState的callBack
在setState方法中传入一个回调函数,在回调中就可以拿到最新的数据
handleAddNumber = () => {
const { count } = this.state;
this.setState({ count: count + 1 }, () => {
console.log('回调中:', this.state.count); // 回调中:1
});};
定时器回调
在非react控制的回调函数中进行操作(定时器、Promise和原生的事件),可以拿到最新的数据
handleAddNumber = () => {
setTimeout(() => {
const { count } = this.state;
console.log(count); // 初始值 0
this.setState({ count: count + 1 });
console.log(this.state.count); //改变后的值 1
}, 0);