【问题标题】:setState not merging but replacing [duplicate]setState 不合并但替换[重复]
【发布时间】:2018-12-04 10:20:41
【问题描述】:

我有一些状态

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

我失去了其他属性

【问题讨论】:

  • 它是因为您将新值分配给主题,而不是合并旧值和新值。像这样更新它:theme: { ...prevState.theme, background: { bgType: 'colour', value: color.hex } },

标签: reactjs setstate


【解决方案1】:

如果您只想在主题中正确设置背景,则需要对主题使用展开语法,而不是像这样的状态

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

【讨论】:

  • 对于真正的深度合并,他也应该传播 state.theme.background obj
  • @DannyDelott,正如 OP 案例中提到的,他似乎没有合并背景值,因此我决定省略这部分。但肯定会在我的答案中添加这部分
【解决方案2】:

也传播内部对象:

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

【讨论】:

    【解决方案3】:

    你必须传播theme对象:

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

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多