Reactjs 设置状态不合并而是替换
我有些状态Reactjs 设置状态不合并而是替换,reactjs,setstate,Reactjs,Setstate,我有些状态 state = { theme: { background: { bgType: 'colour', value: '#449dc7' }, primary: '#4d5a66', secondary: '#476480', }, }; 当我尝试更新嵌套属性(如background时,我调用setState,如下所示 this.setState(prevState => ({ ...prevState, th
state = {
theme: {
background: { bgType: 'colour', value: '#449dc7' },
primary: '#4d5a66',
secondary: '#476480',
},
};
当我尝试更新嵌套属性(如background
时,我调用setState
,如下所示
this.setState(prevState => ({
...prevState,
theme: { background: { bgType: 'colour', value: color.hex } },
}));
然而,这只是将状态替换为
theme: { background: { bgType: 'colour', value: color.hex } },
我丢失了其他属性如果您想在主题中仅正确设置背景,则需要对主题使用扩展语法,而不是像状态一样使用扩展语法
this.setState(prevState => ({
theme: { ...prevState.theme, background: { bgType: 'colour', value: color.hex } }
}));
如果你想把背景值也合并起来,你需要像这样分散它
this.setState(prevState => ({
theme: { ...prevState.theme, background: {
...prevState.theme.background,
bgType: 'colour', value: color.hex
}}
}));
同时展开内部对象:
this.setState(prevState => ({
...prevState,
theme: {
...prevState.theme,
background: {
...prevState.theme.background,
bgType: 'colour', value: color.hex
}
},
}));
您必须传播
主题
对象:
this.setState(({ theme }) => {
return { theme: { ...theme, background: { bgType: 'colour', value: color.hex } } };
});
对于真正的深度合并,他应该将state.theme.background对象扩展为well@DannyDelott,如OP案例中所述,他似乎没有合并背景值,因此我决定省略该部分。但肯定会在我的答案中添加这一部分,因为您将新值分配给主题,而不是合并旧值和新值。更新如下:
theme:{…prevState.theme,背景:{bgType:'color',value:color.hex},