Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 设置状态不合并而是替换_Reactjs_Setstate - Fatal编程技术网

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