javascript - Replacing new state in react redux reducer without making a copy -
if have replacing entirety of slice of state, still have use object.assign or spread operator make copy of original state , replace new state, or can return new state in reducer?
const fetching = (state = { isfetching: false }, action) => { switch (action.type) { case 'requesting': return object.assign({}, state, { isfetching: true } ) case 'receive_pokemon_type_info': return object.assign({}, state, { isfetching: false } ) default: return state } }
vs.
const fetching = (state = { isfetching: false }, action) => { switch (action.type) { case 'requesting': return { isfetching: true } case 'receive_pokemon_type_info': return { isfetching: false } default: return state } }
there couple of things going on here. basically, if state only consists of boolean variable, creating new object enumeration ok. however, if state consists of other things, doing object.assign should work.
however (and isn't there 'however'), if state complex - consists of other objects doing object.assign not copy fields - copied references not values. example, if state consists of "currentlyselectedpokemon" field there value pokemon object, object.assign copy reference pokemon object. won't copy object itself. show more easily, @ code below - prints "value2" obj2.
var obj1 = { field: { subfield: "value" } }; var obj2 = object.assign({}, obj1); obj1.field.subfield = "value2"; console.log(json.stringify(obj2, null, 2));
there 2 ways around this. first use immutable library state. however, found overhead of converting complex objects immutable , provided enough complexity introduced unnecessary bugs. this:
const fetching = (state = { isfetching: false }, action) => { switch (action.type) { case 'requesting': const newstate = json.parse(json.stringify(state)); newstate.isfetching = true; return newstate; case 'receive_pokemon_type_info': const newstate = json.parse(json.stringify(state)); newstate.isfetching = false; return newstate; default: return state } }
it turns out json.parse(json.stringify(object)) fast reliable way make copy of vanilla java object. strips functions (which want). , it's fast because browsers implement functions in native code.
Comments
Post a Comment