我正在 React 中创建一个页面,以使用 isChecked
过滤在我的 state
中定义的属性,如下所示:
this.state = {
countries: [
{ "id": 1, "name": "Japan", "isChecked": false },
{ "id": 2, "name": "Netherlands", "isChecked": true },
{ "id": 3, "name": "Russia", "isChecked": true }
//...
],
another: [
{ "id": 1, "name": "Example1", "isChecked": true },
{ "id": 2, "name": "Example2", "isChecked": true },
{ "id": 3, "name": "Example3", "isChecked": false }
//...
],
//... many more
};
我正在创建一个函数 resetFilters()
以将我的 state
中的所有 isChecked
设置为 false:
resetFilters() {
// in reality this array contains many more 'items'.
for (const stateItemName of ['countries', 'another']) {
// here i try to create a copy of the 'item'
const stateItem = [...this.state[stateItemName]];
// here i set all the "isChecked" to false.
stateItem.map( (subItem) => {
subItem.isChecked = false;
});
this.setState({ stateItemName: stateItem });
}
this.handleApiCall();
}
我的问题是:我似乎直接修改state
,这是错误的,according to the docs 。即使我的函数似乎可以工作,当我删除行 this.setState({ stateItemName: stateItem });
时,它也会似乎工作,并且当我控制台日志 stateItem
和 this.state[stateItemName]
它们始终相同,即使我使用的是扩展运算符,它应该创建一个副本。我的问题:这怎么可能/我做错了什么?
最佳答案
这是因为扩展语法仅进行浅复制。如果要进行深度复制,还应该将内部对象分散到每个数组中。
for (const stateItemName of ['countries', 'another']) {
const stateItem = [...this.state[stateItemName]];
const items = stateItem.map( (subItem) => ({
...subItem,
isChecked: false,
}));
this.setState({ [stateItemName]: items });
}
关于reactjs - react : setState with spead operator seems to modify state directly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59491784/