这个问题在这里已有答案:
我想知道,这是在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中设置对象状态的正确方法
您不应该通过为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>
);
}
}
更新状态的正确方法是使用this.setState函数。
updateName() {
this.setState(oldState, {...oldState, name: "new name"});
}