javascript - 如何将新对象添加到嵌套在 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 减速器返回修改后的状态
解决方案
您可以使用 map 函数来修改您的状态,如下所示:
const newState = state.map((s, idx) => {
// Modification needed elemet
if (idx === 0) {
return {
...s,
someNestedArrayProperty: someNestedArrayProperty
}
}
// Modification not needed
else {
return s;
}
})
推荐阅读
- javascript - 悬停时更改元素时的动画
- python - flask-sqlalchemy 中每组最高的 n
- objective-c - NSButton Push On Push Off 类型
- javascript - 如何保持绝对路径规则从 ts 编译到 js 文件?
- r-markdown - 编织到 Word 文档时在 Rmarkdown 中重置页面计数器
- kubernetes - 如何在 EKS 中编辑 appsettings.json
- python - 在 Python 中创建用于更新记录的第二个表单
- android - 在 Android 中查看针对浏览器与外部应用程序的意图
- react-native - 如何使用“require”为 React bootstrap Card img src 添加一个 prop url
- python - python click -- 动态分组命令全部在一个函数中