setState 不是合并而是替换

setState not merging but replacing

我有状态

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

您必须传播 theme 对象:

this.setState(({ theme }) => {
  return { theme: { ...theme, background: { bgType: 'colour', value: color.hex } } };
});