Reputation: 931
I tried to do a simple counter with react, and I found that ++
doesn't work. I wonder why.
This worked
..
addCount() {
this.setState({count:this.state.count+1})
}
..
But this will not work
..
addCount() {
this.setState({count:this.state.count++})
}
..
You can try it here https://jsfiddle.net/Lwvbe2o2
Upvotes: 2
Views: 3541
Reputation: 55448
Because x++
expression first returns the value of x
then it increments it, while ++x
first increments it, then returns that incremented value.
Just for experimentation purposes, you can verify this by using the preincrement like this
// Don't do this, it's just to explain why it works.
addCount () {
this.setState({count: ++this.state.count})
}
Then it'll do what you want, however it's not idiotmatic, because it does mutate directly this.state.count
.
In ReactJS you don't want to mutate this.state.count
directly, so your first example is more idiomatic:
addCount () {
this.setState({count: this.state.count + 1})
}
MDN postfix/prefix increment operator ++
Upvotes: 6
Reputation: 446
When you do ´a = b++´, you first assign the value of b to a, then you increment b. It's called post incrementation. In your example it's the same : ´count´ will be equal to ´this.state.count´ (So the value will be the same) and then you increment ´this.state.count´, but it will be replace by ´count´ when setState finish because you change the state. setState is here to set your variable, don't mutate it in this method.
Your first proposition is the way to do what you want.
Hope this helps !
Upvotes: 0