In reducers,we always use Object.assign({},state,newState)
to save a state. But assign()
doesn't support deepcopy,because this method only copy a reference of multi-level object. This is my code in program.
const menuListState={
menuList: {},
menuListLoading:false
}
function getMenuList(state=menuListState,action=defaultAction){
switch(action.type){
//menuList begin
case actions.GET_MENULIST_SUCCESS:
return Object.assign({},state,{
menuList:action.data,
menuListLoading:false
});
default:
return state;
}
}
The property menuList
is a multi-level Object. And when action.data
changes, will state.menuList
be changed immediately before the method assign()
work?
Copy an Object With Object.assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.
To start using Lodash in React, you need to:Install Lodash by running npm install lodash. Import Lodash to your project by writing import _ from lodash.
You can use JSON.stringify
to stringify an object, and use JSON.parse
to parse your result string into an object, you will get your new object same with the one you want to deeply copy.
Example:
let copiedObject = JSON.parse(JSON.stringify(originalObject))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With