【发布时间】:2017-08-16 13:20:06
【问题描述】:
如何清除 react 状态变量(Array)中已有的数据,并为其分配另一个数组。我尝试了下面的东西,但它不起作用。
itemsChanged(items) {
this.setState({item : []}) //item is my state variable
this.setState({item : items})
console.log("ITEMS : ",this.state.item) //this will not print the updated value
}
提前致谢
【问题讨论】:
-
设置
this.setState({ item: items })如果它是不同的项目集合,则应该已经覆盖现有数组。setState是异步的,因此您的控制台可能会在操作实际完成之前触发 -
要检查结果状态,您需要像这样在处理程序中移动 console.log:
this.setState({item : []}, function() {console.log("ITEMS : ",this.state.item)})
标签: javascript arrays reactjs redux react-redux