gpt4 book ai didi

reactjs - react : setState with spead operator seems to modify state directly

转载 作者:行者123 更新时间:2023-12-04 10:50:36 25 4
gpt4 key购买 nike

我正在 React 中创建一个页面来过滤在我的 state 中定义的属性与 isChecked像这样:

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()设置所有 isChecked在我的 state 中为假:
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 }); 时它似乎也可以工作,当我控制台日志 stateItemthis.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com