例如,我如何使用 key: 1311
更新对象并返回更新后的状态?假设我不知道它的确切位置......只知道它的键值。
state = {
iow: [
{
key: 1,
iow_description: "EARTH WORK",
unit: null,
rate: null,
children: [
{
key: 11,
iow_description: "Sub-head",
unit: null,
rate: null
},
{
key: 12,
iow_description: "Sub-head",
unit: null,
rate: null,
children: [
{
key: 121,
iow_description: "Sub-head",
unit: "cu.m",
rate: 100.0
}
]
},
{
key: 13,
iow_description: "Sub-head",
unit: null,
rate: null,
children: [
{
key: 131,
iow_description: "Sub-head",
unit: null,
rate: null,
children: [
{
key: 1311,
iow_description: "Sub-head",
unit: "each",
rate: 200.0
},
{
key: 1312,
iow_description: "Sub-head",
unit: "sq.m",
rate: 200.0
}
]
}
]
}
]
}
]
};
最佳答案
你需要递归
const updateState = (children, key, newData) => {
return children.map(item => {
if(item.children) {
item.children = updateState(item.children, key, newData);
}
return item.key === key ? Object.assign({}, item, newData) : item;
});
};
state.iow = updateState(state.iow, 131, {iow_description: "new value", rate: 123})
关于javascript - 如何更新这样的嵌套状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58512740/