[英]Update Object whose value is an array of objects in an immutable way
我需要更新我的 React 组件中的状态:
状态如下所示:
const state = {
'123': [{
progress: 0;
lastModified: 999;
},
{
progress: 0;
lastModified: 666;
}],
'1234': [{
progress: 0;
lastModified: 111;
},
{
progress: 0;
lastModified: 222;
}]
};
鉴于我知道对象键,例如123
我想更新progress
值,因为我也知道用于查找对象的lastModified
。
如何以不变的方式解决这个问题?
您需要为要修改的对象的所有祖先创建新容器
const knownTarget = '123'; const knownLastModified = 666; const changes = { progress: 100 } const state = { '123': [{ progress: 0, lastModified: 999, }, { progress: 0, lastModified: 666, } ], '1234': [{ progress: 0, lastModified: 111, }, { progress: 0, lastModified: 222, } ] }; const newState = { ...state, [knownTarget]: state[knownTarget].map(item => { if (item.lastModified === knownLastModified) { return { ...item, ...changes }; } return item; }) } console.log(state); console.log(newState);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.