Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

reactjs - How to use the 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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

setState is an async function. React may batch a bunch of setStates together. So the value of this.state.count is the value at the time you make the request.

A better solutions to call a function that gets evaluated at the time the setState gets executed.

this.setState((prevState, props) => ({
    counter: prevState.counter + 1
})); 

from https://facebook.github.io/react/docs/state-and-lifecycle.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...