Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deepcopy in React

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?

like image 760
ThiagoSun Avatar asked Aug 31 '16 04:08

ThiagoSun


People also ask

How do you Deepcopy an object?

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.

What is a deep copy?

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.

How add Lodash in React?

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.


1 Answers

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))
like image 196
passion Avatar answered Sep 24 '22 10:09

passion