Aminadav Aminadav - 3 months ago 23
React JSX Question

How to uses increment operator in React

Why when I am doing

this.setState({count:this.state.count*2})
it is working, but when I am doing:
this.setState({count:this.state.count++})
it is not working?

Why, and how to fix it?

Full code:

var Hello = React.createClass({
getInitialState:function(){
return {count:parseInt(this.props.count)}
},
a:function(){
this.setState({count:this.state.count++})
console.log(this.state)
},
render: function() {
console.log(this.state)
return <div onClick={this.a}>Click to increment the counter<b> {this.state.count} </b></div>;
}
});

ReactDOM.render(
<Hello count="1" />,
document.getElementById('container')
);


But this code is working:

a:function(){
this.setState({count:this.state.count*2})
console.log(this.state)
},


JSFiddle: https://jsfiddle.net/69z2wepo/55100/

Answer

By doing this.state.count++, you mutate the state, because it's the same thing than doing this.state.count += 1. You should never mutate the state (see https://facebook.github.io/react/docs/component-api.html). Prefer to do that instead:

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