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

标签 reactjs

我正在 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 }); 时,它也会似乎工作,并且当我控制台日志 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/

相关文章:

html - 在 HTML/CSS 中实现下拉列表

reactjs - 如何根据formik中的另一个字段设置一个字段的输入值?

css - 如何在 React 应用程序中加载 css?

reactjs - 如何使用现有的登录 Chrome 用户配置文件正确设置 VS Code 以在 Chrome 中进行调试?

javascript - componentDidMount 生命周期方法中的条件异步操作不断循环

javascript - React-js 如何触发 'BeforeInstallPromptEvent' 启动 "pop up"添加到主屏幕

node.js - 如何使 "npm run start"退出并显示代码 0?

javascript - 从不同组件获取功能时遇到问题

javascript - react 路由器路径内的问号

javascript - 真的有必要使用react-bootstrap提供的组件吗?