JZ.*_*JZ. 5 javascript setstate reactjs
我想清除阵列,但我遇到了麻烦.
this.setState({warnErrorTypes:[]})
我不确定我是在处理竞争条件,还是具体问题是什么,但我可以看到,在我需要将其值重置为[]的情况下,我的数组的值始终是错误的.
如何用[]然后随后[3]替换包含[1,2]的数组,其中以下为真:
this.setState({warnErrorTypes:[]})[2,1,3]当我期望它时,上面逻辑的结果总是如此[3].
setState 是原子的,所以你不能只发出多个setState()调用并希望事情能够工作,你要么必须等待状态更新再更新它,要么影子实例变量.
选项1:
moo: function() {
this.setState({
myarr: []
}, function() { // called by React after the state is updated
this.setState({
myarr: [3]
});
});
}
Run Code Online (Sandbox Code Playgroud)
这非常麻烦.另一种选择是使用您在需要时作为状态发送的"真实"实例变量.
选项2:
getInitialState: function() {
this.mylist = [];
return {
myarr: this.mylist
};
},
...
moo: function() {
this.mylist = [];
for(var i=0; i<10; i++) {
this.mylist.push(i);
}
this.setState({ myarr: this.mylist });
}
Run Code Online (Sandbox Code Playgroud)
请记住,更新状态意味着您已经更改了需要重新渲染的组件的某个方面,因此如果您不打算重新渲染组件,请不要使用setState,例如清除阵列和重新填充它之间.单独做这些事情,只有在你完成后才更新状态.
选项3:
您还可以通过取出状态值,运行更新,然后重新绑定来完成此操作,而无需构建持久性实例变量:
moo: function() {
var list = this.state.myarr;
while(list.length > 0) { list.splice(0,1); }
for(var i=0; i<10; i++) { list.push(i); }
this.setState({ myarr: list });
}
Run Code Online (Sandbox Code Playgroud)
净效果是相同的:您只在数据处于某种稳定配置时更新您的UI,因此如果您认为setState()在渲染之间不止一次调用,那就是一个问题:每次setState()调用都可能触发渲染,连续setState()可能"如果你不等待它们首先绑定,则覆盖"彼此".
| 归档时间: |
|
| 查看次数: |
15550 次 |
| 最近记录: |