【问题标题】:How to change state of key inside state object in React? [duplicate]如何在 React 中更改状态对象内的键状态? [复制]
【发布时间】:2020-03-21 03:30:57
【问题描述】:

我在React.Component 类中有以下状态:

this.state = {
  stuff: {
    stuffData: [],
    loading: true,
  },
  moreStuff: {
  ...
  }
}

在函数内部,单击按钮后,我想将stuff 的状态更新为loading

如果我这样做,它会起作用:

const { stuff } = this.state;
const newStuff = stuff;
newStuff.loading = true;
this.setState({ stuff: newStuff };

但我想这样做(没有得到预期的结果):

const { stuff } = this.state;
this.setState({ stuff: {loading: true, ...stuff } });

我错过了什么?

【问题讨论】:

  • 您正在使用扩展运算符覆盖加载的值。我也认为,第一种方法很好
  • 你反其道而行之。应为{ ...stuff, loading: true },与Object.assign(stuff, { loading: true }) 相同。 stuff 是基础对象,您正在覆盖加载变量。
  • @Santa'sLittleHelper 这不一样,因为Object.assign 会变异stuff,而传播不会变异stuff
  • @EmileBergeron 你是对的。我的错。

标签: javascript reactjs


【解决方案1】:

您首先复制您的对象,然后更改您要更改的值。

const { stuff } = this.state;
this.setState({ 
   stuff: {
       ...stuff, 
       loading: true 
   } 
});

因为 如果rest = {a:2, b:3}

  • {a: 1, ...rest} 会给你{a:2, b:3}

  • {...rest, a: 1} 会给你{a:1, b:3}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2020-07-31
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2016-08-07
    相关资源
    最近更新 更多