【发布时间】:2016-10-06 08:56:59
【问题描述】:
我有一组处于状态的对象:
this.state = {
items: [
{id: 1, someattr: "a string", anotherattr: ""},
{id: 2, someattr: "another string", anotherattr: ""},
{id: 3, someattr: "a string", anotherattr: ""},
]
}
我需要能够根据 id 属性搜索 items 数组,然后更新 objects 属性。
我可以使用 id 参数通过数组上的filtering 或finding 获取对象。
我遇到的问题是更新数组,然后更新状态而不发生突变。
//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 更新状态,以便覆盖初始查找操作返回的对象?
【问题讨论】:
-
为什么不再使用 object.assign 呢?
-
您能否举个例子,因为我不确定它是如何工作的?
-
const newState = Object.assign(this.state.items,matched) this.setState({items: newState}) ...如果我理解正确
-
为什么不能直接使用
this.state = { items: { 1: { someattr: ... }, 2: { ... }, ... } };?this.state.items[id] = { ...this.state.items[id], someattr: 'a new value' }.
标签: reactjs ecmascript-6