I’m new to learning React. I have a class ListItem that extends the React.Component class.
I’m curious why there’s a difference in console outputs and what would be best practice between using this.setState({ stateItem : newValue })
and just assigning the state directly with this.state.stateItem = newValue
.
Here’s my example (I’ve tried to just limit the code to the area of the component in question).
In both scenarios, the component has an initial state.
constructor(props) {
super(props);
this.state = {
itemStatus : false
}
}
render() {
return (
<li>
<input type='checkbox' id="item-1" name="item-1" onClick=
{this.toggleItemStatus.bind(this)} />
<label htmlFor="item-1">{this.props.title}</label>
</li>
);
}
Then comes the part in Question
toggleItemStatus() {
console.log(this.state.itemStatus); //Outputs false
this.state.itemStatus = !(this.state.itemStatus);
console.log(this.state.itemStatus); //Outputs true
}
Versus the other approach
toggleItemStatus() {
console.log(this.state.itemStatus); //Outputs false
this.setState({
itemStatus : !(this.state.itemStatus)
});
console.log(this.state.itemStatus); //Outputs false
}