react中this.setState到底能不能进行运算?我按照react 小书的教程写但是发现结果不对。。。我这里的count每次点击都会+2,相当于是最后一个this.setState把前面的都覆盖了。?
2 回答
心有法竹
TA贡献1866条经验 获得超5个赞
this.setState 是异步的, 需要在回调函数里面去取值
ES6
this.setState({
count: 0}, () => {
console.log(this.state.count);
})ES5
this.setState({
count: 0}, function(){
console.log(this.state.count);
})
噜噜哒
TA贡献1784条经验 获得超7个赞
setState是异步的,也就是说:并不是setState被调用后state就会立即改变,它只是保证在之后的某刻会被改变。因此,你的第2,3个setState中的this.state.count依旧是undefined。
另外,为了优化性能,在一定时间内像这种传对象字面量方式调用setState是会被批量处理的,前两个setState会被合并到第三个调用中,也就是说只有第三个会起作用。
为了达到你原来代码的意图,你应该使用updater函数
this.setState((prevState) => ({ ...prevState, count: 0 }));
this.setState((prevState) => ({ ...prevState, count: prevState.count + 1 }));
this.setState((prevState) => ({ ...prevState, count: prevState.count + 1 }));
添加回答
举报
0/150
提交
取消
