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

What is the proper way to handle component's state in React?

本文关键字:方法 是什么 状态 React 处理 组件      更新时间:2023-09-26

我见过人们使用setState的方式:

this.setState( {enteredlocation: newLocation});

目前我像这样写信给状态:

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

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

稍后还将集成 Redux,但现在,我正在尝试逐部分理解。

取而代之的是:

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

。做:

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

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