如何清除反应状态变量(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'是异步的,所以你的控制台可能会在动作实际完成之前触发。 – LoganRx
Pl通过这个:https:// stackoverflow。com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately/42593250#42593250 – Dev
要检查结果状态,您需要在处理程序中移动console.log,如下所示:'this。 setState({item:[]},function(){console.log(“ITEMS:”,this.state.item)})' –