无法在React.js中更新状态

时间:2016-05-03 04:00:38

标签: reactjs

我正在使用React和ES2015。我在我的州有这个:

this.state = { info: {
            merchandise: {
              label: '',
              visible: false
            },
            hotels: {
              label: '',
              visible: false
            }
    }
}

我尝试使用以下代码更新状态:

this.setState({info.merchandise.label: "New Label"})

但是我收到错误,而我可以记录this.state.info.merchandise.label的值而没有任何问题。我做错了什么?

3 个答案:

答案 0 :(得分:0)

我相信您只能在setState()直接属性上使用this.state

在这种情况下你可以做的是

  1. 制作一份您想要使用的state财产的浅色副本
  2. 在副本中更改要更改的属性。
  3. 该副本现在具有您想要的更新属性。因此,请将其分配回this.state
  4. 像这样:

    let temp = Object.assign({}, this.state.info);
    temp.merchandise.label = "New Label";
    this.setState(info: temp);
    

答案 1 :(得分:0)

您可以执行以下操作,

let newState = this.state;
newState.info.merchandise.label = "New Label";
this.setState(newState);

答案 2 :(得分:0)

根据React's setState doc

  

执行nextState到当前状态的浅层合并

这意味着您应该提供有效的nextState对象作为方法的参数。 {info.merchandise.label: "New Label"}在语法上不正确,这就是您收到错误的原因。

  

将this.state视为不可变。

这只是意味着如果你想改变状态对象中的一些属性,你不应该直接改变它,而是用一个包含修改的新对象替换它。

在您的情况下,状态对象包含多个嵌套对象。如果你想修改一个" leaf"对象的属性,您还必须为树上的每个包含对象提供新对象(因为它们中的每一个都具有在该过程中发生变化的属性)。使用Object.assign()创建新对象,您可以写:

// new "leaf" object:
const newMerchandise = Object.assign({}, this.state.info.merchandise,
    {label: "New Label"});

// new "parent" object:
const newInfo = Object.assign({}, this.state.info,
    {merchandise: newMerchandise});

// new state ("parent") object:
const newState = Object.assign({}, this.state,
    {info: newInfo});

// eventually:
this.setState(newState);

顺便说一下,当你的结构趋于“平坦”时,你会注意到处理状态对象会更容易。而不是"深深嵌套"。

相关问题