0

I need to change the state by using a click. This is my code:

var List = React.createClass({

    getInitialState : function() {

      return {data : [], currentPage : 0} ;

    },
    componentDidMount : function() {
      this.getData() ;
    },
    getData : function() {
      console.log(this.state.cuurrentPage) ;
      //this is getting data from the server
    },
    incrementPage : function() {
      this.setState({currentPage : this.state.currentPage + 1}) ;
      this.getData() ;
    },
    return : function() {
     <button onClick={this.incrementPage}>More</button>
    }

})

but the changes happen only after the first click. After the first click I get the default state "0", but when I do the second click I get changed state "1".

Why is it works so? And how can change the state after the first click?

7
  • is it a typo: return: function().. ?? It should be render() Commented Nov 8, 2015 at 23:09
  • Yes, you are right. My mistake when i was copying the code to here, but anyway this doesn't work as i want. Commented Nov 8, 2015 at 23:13
  • have you tried to run just console.log in componentDidMount .. Seams like its not called at all Commented Nov 8, 2015 at 23:17
  • Yes, componentDidMount works. Commented Nov 8, 2015 at 23:21
  • Please read the big red box in the documentation: "setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.". The state gets updated just fine, but you are reading from the state before it was updated. Commented Nov 8, 2015 at 23:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.