
How to change state in Redux
This is a trap for redux users. We have to pay attention to this rule when using redux. Do you care about whether the object you are about to change is mutable or immutable?
Example
# storeperson = {
name: 'John Doe',
age: 26,
booksIHave: ['A', 'B', 'C']
}
# containerexport default connect(
state => ({
person = state.person
}),
dispatch => bindActinonCreators({ updatePerson }, dispatch)
)
There might be data like above. If we want to update the name of the first one in booksIHave, what should we do?
Don’t do like this
updatePerson({...person, booksIHave[0] = 'D'})
If we do like this, Redux doesn’t work rightly. For example, re-render doesn’t work, prevProps and currentProps are the same (it happened to me…).
Best Practice
newBooksIHave = ['D', 'B', 'C']
updatePerson({...person, booksIHave: newBooksIHave})
In this case, Redux works!
Reason
Redux makes use of a shallow comparison, which means not whether object itself was changed but whether a reference changed matters.