React For Loop with onClick inside

0

I am working with React, I have the following code:

var rows = [];
for(var i = 1; i <= this.state.numberOfPages; i++) {
    rows.push(<li key={i.toString()} onClick={() => this.getResults(i)}><a href="#">{i}</a></li>)
};

The getResults() function is as simple as this:

getResults: function(page = this.state.currentPage) {
    console.log(page);
},

The variable this.state.numberOfPages is equal to 3. The problem occurs when I click on the <li> , in the console it always prints 4. However, the values of <li> are displayed perfectly on the screen. It is as if when the parameter that is going to be passed to the function is assigned, the last value of i will be evaluated.

Is there any solution you can think of?

Thank you very much!

    
asked by Genarito 26.12.2016 в 20:59
source

1 answer

3

The error is when assigning the callback to the onClick event

onClick={() => this.getResults(i)}

you should do it like this

onClick={this.getResults.bind(this, i)}

Also in the declaration of the function getRessults you are not printing 'i' you are printing the current page this.state.currentPage.

I guess what you want is to define it as

getResults: function(page) {
    console.log(page);
}
    
answered by 27.12.2016 / 22:53
source