I would like to know, which is the correct method to set state of an object in ReactJS.
Please find my sample code:
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>
);
}
}
This is my sample code to update name. Here, name is updated using setState
and results in the output 'Updated'.
If updateName()
is rewritten as,
updateName(){
this.state.name = 'Updated';
}
and then printing the name, it gives the same result. I would like to know, the correct method to set the state of an object in ReactJS