[英]How to add a new object to an array of objects that is nested inside an array of objects in 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 reducer 返回修改后的状态
您可以使用 map 函数来修改您的状态,如下所示:
const newState = state.map((s, idx) => {
// Modification needed elemet
if (idx === 0) {
return {
...s,
someNestedArrayProperty: someNestedArrayProperty
}
}
// Modification not needed
else {
return s;
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.