I have an array of objects in state:
this.state = {
items: [
{id: 1, someattr: "a string", anotherattr: ""},
{id: 2, someattr: "another string", anotherattr: ""},
{id: 3, someattr: "a string", anotherattr: ""},
]
}
I need to be able to search the items array based on the id property and then update the objects attributes.
I can get the object by filtering
or finding
on the array using the id param.
What I'm having trouble with is then updating the array and then subsequently updating state without mutation.
//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);
At this point I have a matching object and can update it's properties using object spread:
const matchUpdated = { ...match, someattr: 'a new value'};
My question is how do i then update the state with matchUpdated
so that it overwrites the object returned by the initial find operation?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…