Reaction, about non-mutating state
Suppose I have a state
state = {
inner1: {
inner2: {
foo: var1
}
}
}
I want to upgrade foo
to var2
.
Do I have to create a copy state
inner1
inner2
for noowEqual to see the replacement state
inner1
inner2
?
in code, it would be something like
newState = _.merge({}, state, {
inner1: {
innner2: {
foo: var2
}
}
})
(Although I'm not entirely sure how _.merge works, it seems like it comes across an intuitive interface)
So, conceptually, I create a shallow copy before (nested level), I find the object I want to modify.
Or would it be more appropriate to update only inner2
?
var { inner2 } = state.inner1
var newInner2 = _.merge({}, inner2, {
foo: var2
})
state.inner2 = newInner2
source to share
Instead of using Lodash, you can simply use the spread operator. This example assumes there are more properties on inner1
and off inner2
than your question. If not, the spreads are completely out of date.
this.setState((prevState) => ({
inner1: {
...prevState.inner1,
inner2: {
...prevState.inner2,
foo: var2,
},
},
}));
source to share