I am following a tutorial where I have the following class method:
incrementarScore() {
this.setState({
score: this.state.score += 1
});
}
The code above works perfect.
If I change the line inside the setState() method to this:
score: this.state.score += 1
Also works
but if I change it to this:
score: this.state.score ++
It no longer works, which seems more than strange to me.
Could someone explain to me why?
You are confusing yourself with what the operator does
++
:++ variable
First increment the current value. Then, it returns that value (already incremented).
variable ++
First get the current value ; then increment it.
This last point is your case. Arguably, the shape
variable ++
copies the current value. The original value is indeed incremented... but it returns to you the value before the increment.In your case, your code actually runs like this:
You can solve it using the other way:
It's because the increment operator can be used as a prefix or postfix. Depending on how you use it, it will return the new value sooner or later.