我有以下目的。当用户单击按钮时,将为该对象分配一个新值。
state = { title: '', id: '', imageId: '', boarding: { id: '', test: '', work: { title: '', id: '' } } }
我更新的对象如下所示:
state = { title: 'My img', id: '1234', imageId: '5678-232e', boarding: { id: '0980-erf2', title: 'hey there', work: { title: 'my work title', id: '456-rt3' } } }
现在,我只想更新状态内的工作对象,并使所有内容保持不变。Object.assign()当对象未嵌套但对嵌套感到困惑时,我正在使用。
Object.assign()
Object.assign({}, state, { work: action.work });
我的action.work具有整个工作对象,但现在我想将其设置为登机,但这将代替登机中所有我想要的东西。
您应该手动合并深层对象属性,请尝试以下操作:
Object.assign({}, state, { boarding: Object.assign({}, state.boarding, { work: action.work } });
或使用传播算子
{ ...state, boarding: { ...state.boarding, work: action.work } }