Because the principle of the Redux state, the state always is read-only. And if we want to update some variable, we always have to return a new value. The problem is javascript always pass object by reference, and redux store could not recognize Array element 's data changes because Array reference is not changed. The right way to update
For example, let's assume we have an array in our state name "events" and contains many event objects.
E.g. the right way to update:
function updateEvnet(state, ID, data ) {
let events = [...state.events];
for (let index = 0; index < events.length; ++index) {
let eventData = events[index];
if (eventData.ID !== ID) {
continue;
}
const event = {
...eventData,
data
};
events[index] = event;
break;
}
return {
...state,
events : events
}
}
Using spread syntax(es6) could easily make copy of a variable, see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
let events = [...state.events] is equal to:
let events = [];
for(let index =0; index < state.events.length; ++index){
events.push( state.events[index] );
}