Thian Kian Phin Thian Kian Phin - 2 months ago 6
React JSX Question

The increment ++ operator doesn't work for setting react state

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

Answer

Because x++ expression first returns the value of x then it increments it

While ++x first increments it, then returns that incremented value;

You can use the preincrement like this

addCount() {
  this.setState({count:++this.state.count})
}

Ref. MDN postfix/prefix increment operator ++