【问题标题】:How to set state of an object in ReactJS? [duplicate]如何在 ReactJS 中设置对象的状态? [复制]
【发布时间】:2019-08-16 20:28:51
【问题描述】:

我想知道,在 ReactJS 中设置对象状态的正确方法是什么。

请找到我的示例代码:

class MyComponent extends Component {
  constructor(props) {
    this.updateName = this.updateName.bind(this);
    this.state = {
      name: "Sample code"
    };
  }
  updateName() {
    this.setState(name: "Updated");
  }
  componentDidMount() {
    this.updateName();
  }
  render() {
    return (
      <div>
        <label>{this.state.name}</label>
      </div>
    );
  }
}

这是我更新名称的示例代码。在这里,使用setState 更新名称并导致输出“更新”。

如果updateName()被改写为,

updateName(){
  this.state.name = 'Updated';
}

然后打印名称,它会给出相同的结果。 我想知道,在 ReactJS 中设置对象状态的正确方法

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您不应通过为this.state.name 分配新值来直接改变状态对象。您应该使用setState 方法并给它一个应该更新状态的对象。

    class MyComponent extends Component {
      constructor(props) {
        this.updateName = this.updateName.bind(this);
        this.state = {
          name: "Sample code"
        };
      }
    
      componentDidMount() {
        this.updateName();
      }
    
      updateName() {
        this.setState({ name: "Updated" });
      }
    
      render() {
        return (
          <div>
            <label>{this.state.name}</label>
          </div>
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      更新状态的正确方法是使用 this.setState 函数。

      updateName() {
         this.setState(oldState, {...oldState, name: "new name"});
      }
      

      参考:https://reactjs.org/docs/state-and-lifecycle.html

      【讨论】:

        猜你喜欢
        • 2022-07-07
        • 1970-01-01
        • 2018-10-21
        • 2020-08-26
        • 2021-10-17
        • 1970-01-01
        • 2020-04-17
        • 2022-12-11
        • 1970-01-01
        相关资源
        最近更新 更多