在React中处理组件状态的正确方法是什么?

时间:2016-07-13 02:20:12

标签: javascript reactjs state

我见过人们使用setState方式:

this.setState( {enteredlocation: newLocation});

目前我正在写这样的州:

this.state.id.push({"no" : length , "location": this.state.enteredlocation});

更新状态的正确方法是什么?

我也将在稍后整合Redux但是现在,我试图逐个理解。

1 个答案:

答案 0 :(得分:1)

而不是:

this.state.id.push({"no" : length , "location": this.state.enteredlocation});

...执行:

this.setState({ 
  id: this.state.id.concat({
    "no": length, 
    "location": this.state.enteredlocation
  })
});

这将确保id是一个新的数组引用,而不是具有不同内容的相同引用。

相关问题