In the todoMVC example of a redux project, the todos reducer has the following lines:
export default function todos(state = initialState, action){ ... case EDIT_TODO: return state.map(todo => todo.id === action.id ? Object.assign({}, todo, { text: action.text }) : todo ) }
This piece of code is related to updating a specific todo object. My question here is that since state.map () will always return a new array. Then you need to do the following:
Object.assign({}, todo, { text: action.text})
Could it be:
Object.assign(todo, { text: action.text})
UPDATE
I understand the difference between Object.assign({}, blah...) vs Object.assign(obj, blah...) . Let me rephrase my question:
Redux wants reducers to return a new state instead of mutating an existing state. I understood. In my example, I have an array of objects. I want to change the order of the first two elements. Check out the jsbin example here .
- Since Array.map always returns a new array , the reference to the returned gurranteed array will be new. Check it out.
- However, the elements in the returned array are not all new . The reference to the first two elements is new. However, the third element is not. This is the same third element as in the old array.
So my question is about the third element, should I use:
Object.assign({}, third_element) or just return the third_elment
Does Redux require a new array with new references to every object inside it (even if the values ββstored in these new objects are identical to the old objects) or just a new array with updated new elements?
javascript reactjs redux
Cheng
source share