gpt4 book ai didi

javascript - React 中的深度复制

转载 作者:可可西里 更新时间:2023-11-01 02:57:04 27 4
gpt4 key购买 nike

在 reducer 中,我们总是使用 Object.assign({},state,newState) 来保存状态。但是assign()不支持deepcopy,因为这个方法只是复制一个多级对象的引用。这是我的程序代码。

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;
}
}

menuList 属性是一个多级对象。当 action.data 改变时,state.menuList 会在方法 assign() 工作之前立即改变吗?

最佳答案

您可以使用 JSON.stringify 将对象字符串化,然后使用 JSON.parse 将结果字符串解析为对象,您将得到与你想要深度复制的那个。

例子:

let copiedObject = JSON.parse(JSON.stringify(originalObject))

关于javascript - React 中的深度复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39241046/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com