[英]How to add a new object to an array of objects that is nested inside an array of objects in ReactJS?
I am new to ReactJS and JS and always get stuck with updating the state using object spread.我是 ReactJS 和 JS 的新手,总是被困在使用对象传播更新状态。
I have simplified my data as follows and consider the 0th index for the state for my example,我已将我的数据简化如下,并在我的示例中考虑状态的第 0 个索引,
state = [
{
id: "1",
name: "Some name",
someNestedArrayProperty: [
{
id: "1",
name: "Name 1"
},
{
id: "2",
name: "Name 2"
}
]
},
{...}
]
I want to add a newObject into someNestedArrayProperty that I receive from action creator, say我想将一个 newObject 添加到我从动作创建者那里收到的 someNestedArrayProperty 中,例如
newObject = {
id: "3",
name: "Name 3"
}
I am not getting the correct syntax.我没有得到正确的语法。 I tried the following and it is messing up the state.
我尝试了以下操作,但它弄乱了状态。 Below is the simplified code of what I am trying to do in my application,
以下是我在应用程序中尝试执行的操作的简化代码,
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
}
}
];
Note: I am returning the modified state from the Redux reducer注意:我从 Redux reducer 返回修改后的状态
You can use map function to modify your state like following:您可以使用 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.