首页 > 解决方案 > 如何将新对象添加到嵌套在 ReactJS 中的对象数组中的对象数组中?

问题描述

我是 ReactJS 和 JS 的新手,总是卡在使用对象传播更新状态。

我已将我的数据简化如下,并在我的示例中考虑状态的第 0 个索引,

state = [
  {
    id: "1",
    name: "Some name",
    someNestedArrayProperty: [
      {
        id: "1",
        name: "Name 1"
      },
      {
        id: "2",
        name: "Name 2"
      }
    ]
  },
 {...}
]

我想将一个 newObject 添加到我从动作创建者那里收到的 someNestedArrayProperty 中,比如说

 newObject = {
        id: "3",
        name: "Name 3"
      }

我没有得到正确的语法。我尝试了以下方法,它弄乱了状态。下面是我在我的应用程序中尝试做的简化代码,

  let someNestedArrayProperty= [
    ...state[0].someNestedArrayProperty,
    action.someNestedArrayProperty
  ];
  return [
    {
      ...state,
      [0]: {  //I guess the problem is in this line "[0]", but I am not getting the correct syntax
        ...state[0],
        someNestedArrayProperty: someNestedArrayProperty
      }
    }
  ];

注意:我正在从 Redux 减速器返回修改后的状态

标签: javascriptreactjs

解决方案


您可以使用 map 函数来修改您的状态,如下所示:

const newState = state.map((s, idx) => {

    // Modification needed elemet
    if (idx === 0) {
        return {
            ...s,
            someNestedArrayProperty: someNestedArrayProperty
        }
    }
    // Modification not needed
    else {
        return s;
    }

})

推荐阅读