我正在尝试更改 ReactJS 中数组中所有元素的状态,如下所示。这是我的第一个应用程序,所以我不知道这里出了什么问题。
closeState(){
this.state.itemList.forEach(function(itemInd){
this.setState({ itemInd.expState : 0 });
}
});
它给我 Unexpected token
错误
我有
this.state = {
...........
itemList: [],
.....
}
itemList 中的每个元素都有:title、desc、expState
。
最佳答案
我认为你选择了错误的方法来解决这个问题。从你的例子中我了解到你想为 中的每个元素将
., 如果是真的最好这样做expState
设置为 0
itemList
const newItemListState = this.state.itemList.map((itemInd) => {
return Object.assign(itemInd, { expState: 0 });
});
this.setState({ itemList: newItemListState })
在你的例子中你有几个错误
- 你忘记在回调函数后添加
)
你需要为
.forEach
回调设置this
,或者使用arrow function
2.1。
this.state.itemList.forEach(function(itemInd) { }, this);
2.2。
this.state.itemList.forEach((itemInd) => { });
您不能使用此
{ itemInd.expState : 0 }
表达式。
关于javascript - webpack ReactJS : Unexpected token at this. 设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37585934/