我有一个处于状态的对象数组:
this.state = {
items: [
{id: 1, someattr: "a string", anotherattr: ""},
{id: 2, someattr: "another string", anotherattr: ""},
{id: 3, someattr: "a string", anotherattr: ""},
]
}
我需要能够根据 id 属性搜索 items 数组,然后更新对象属性。
我可以通过以下方式获取对象filtering
or finding
使用 id 参数在数组上。
我遇到的问题是更新数组,然后更新状态而不发生突变。
//make sure we're not mutating state directly by using object assign
const items = Object.assign({}, this.state.items);
const match = items.find((item) => item.id === id);
此时,我有一个匹配的对象,并且可以使用对象扩展更新它的属性:
const matchUpdated = { ...match, someattr: 'a new value'};
我的问题是如何更新状态matchUpdated
以便它覆盖初始查找操作返回的对象?