如何在ReactJS中设置对象的状态? [重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我想知道,这是在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更新名称,并输出'Updated'。

如果updateName()被重写为,

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

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

reactjs
2个回答
2
投票

您不应该通过为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>
    );
  }
}

0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.