I have example from React where component update depends on does the props will be object or array type. Using reselect library and Redux store. Does it suppose to be like that, meaning the new object willn't be equal to prevprops? And if it is suppose to work this way, how can I work with the objects and new props in redux so shouldComponentUpdate will work for me when changes with object occur in props?
-
Why would you need to use shouldComponentUpdate manually? Redux automatically instructs the react to re-render if a new state was returned from reducer. I am confused of the question tbh.Sudhanshu Rai– Sudhanshu Rai2020-09-18 13:40:35 +00:00Commented Sep 18, 2020 at 13:40
-
Hello Ashu, did you opened the example? There is no automatically re-render if you will use object there as props. You can see it in console. So when reducer changing the value it willn't affect the render if type is object, but that object will be different from previous one (values will change)Zak the Gear– Zak the Gear2020-09-18 14:16:39 +00:00Commented Sep 18, 2020 at 14:16
Add a comment
|
1 Answer
You have your reducer function wrong, CounterReducer.js, Line 10
return {
...state,
// don't set this directly, this code preserves the reference to the array and react does not updates the
counter: state.counter
// counter: Array.from(state.counter)
};
Check the code I have updated, you are setting the reference in the above code, replace the above code with this.
return {
...state,
//counter is now a new array
counter: [...state.counter]
// counter: Array.from(state.counter)
};
4 Comments
Zak the Gear
Nice thing, Ashu! Thank you. Will search more about this syntax.
Sudhanshu Rai
It's called spread operator, more here, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Zak the Gear
Sure, thank you again, I was know it but not used too much. So here it is needed for object to be converted in elements so it will go in props and will be like an array. But how did you get your decision, meaning how did you know you need to use it here? Just want to get the logic of using this operator in redux.
Sudhanshu Rai
It's not a decision, This is a general rule of thumb and whole react's setState and view updation is based on this You never change your array or object directly, You modify them and return the new array/object, so that react knows that it must update the view since state was updated, must read this stackoverflow.com/a/40309023/8155208