Get over shallow comparison issues?
See original GitHub issueI was working on an issue today that I wasn’t able to explain in other way than shallow comparison.
Essentially I have a state similar to following:
{
meta: {},
contents: [
{ content_type: 1, text:"" },
{ content_type: 2, text:"" },
{ content_type: 1, text:"" }
]
}
there are many content types, this is just a simple example. What I am doing is re ordering these in state to cause re ordering on ui side, ie I can move first object from contents array down or second one up just fine, but when it comes to re ordering 2 object with same content type, it successfully updates the redux state, however react doesn’t re-render the ui, and I came to conclusion that this could be caused by shallow comparison, as objects that switched places are very very similar, only their text fields are different.
I am looking for a way to work around this.
following is how I update my redux state:
...
case STORY_ACTIONS.UPDATE_STORY_CONTENTS:
return { ...state, contents: action.payload }
...
where action.payload is correctly re-ordered contents array, I don’t think this is an issue, as it does update redux state correctly.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:1
- Comments:11 (3 by maintainers)
Top GitHub Comments
@Sunakujira1 I got it! so I was setting key of each storyBlock to index gathered from map() somehow this led to isues, changing this key to something like uniqe random id I generated for each block helps.
This is why I asked about the local state. If you don’t specify the key, components will receive each other’s props on reorder. Which makes reorder slower but that is not the root of the problem.
The root of the problem is you derive local state from initial props in the constructor. But props may be received by the component more than once. When your components receive new props during reorder, you forget to reset the state to reflect those new values.
To do it, you would need to implement
componentWillReceiveProps(nextProps)
that callssetState
ifnextProps.text !== this.props.text
. Adding a key also helps but it heals the symptom rather than the actual cause of the problem.