javascript - Changes to object made with Object.assign mutates source object -
i have following reducer code in react-redux app:
case 'toggle_client_selection': const id = action.payload.id; let newstate = object.assign({}, state); newstate.list.foreach((client) => { if (client.id == id) client.selected = !client.selected; }); console.log(state.list[0].selected + ' - ' + newstate.list[0].selected) return newstate;
if got right - object.assign creates brand new object, console.log displays "true - true" of "false - false". thoughts why behaves , how can avoid behavior?
true, it's not deep copy.
the new object contains reference old list.
here's trick around (there's more "proper" ways might say):
json.stringify original. json.parse string. new object "deep" copy (not sure if that's technically "deep copying"). works fine unless sub-types more complex standard plain old json-acceptable stuff.
Comments
Post a Comment