Javascript 将大型对象上的更新从排列转换为object.assign()
我目前正在使用spread操作符来更新一个大对象,它工作得很好,只是每次我想更新一个对象时,它感觉像allot to typeJavascript 将大型对象上的更新从排列转换为object.assign(),javascript,Javascript,我目前正在使用spread操作符来更新一个大对象,它工作得很好,只是每次我想更新一个对象时,它感觉像allot to type setGlobal((state: any) => ({ ...state, locationData: { ...state.locationData, Config: { ...state.locationData.Config, Enabled: true },
setGlobal((state: any) => ({
...state,
locationData: {
...state.locationData,
Config: { ...state.locationData.Config, Enabled: true },
},
}));
}
}, [onlineResponse]);
我想尝试Object.assign(),但我不能得到相同的结果,我的linter突然爆炸,说我缺少了','和':'
setGlobal((state: any) => ({
const state = Object.assign({}, state, {state.locationData.Config.Enabled : true })
}));
}
}, [onlineResponse]);
在我看来,spread运算符语法看起来更清晰易读,但如果您想实现与
Object.assign相同的功能,那么它将类似于:
Object.assign({}, state, { locationData: { ...state.locationData, config: {...state.locationData.config, Enabled: true }} });
我会坚持使用spread operator,因为它感觉更干净。为了避免大量输入,您可以考虑将代码提取到函数中(但在该函数中,我将保留扩展运算符)。