5

I'm working with React. This is my 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>)
};

getResults() function is as simple as:

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

this.state.numberOfPages is equal to 3. The issue is that, when I click on <li> tags, 4 is always showed in console. However <li> values are showed correctly in the HTML. I can't understand why is always being evaluated the last i value when it is passed by parameter.

A detail:

In React Console, key property are correct too. The problem is with the parameter only.

Thanks in advance and sorry about my English.

Genarito
  • 3,027
  • 5
  • 27
  • 53

1 Answers1

4

As mentioned in the duplicated answer, you need to close over the variable with some inner function. Using map is an easy way to achieve this:

var rows = new Array(this.state.numberOfPages).fill(0).map( ( zero, index ) =>
    <li key={index} onClick={() => this.getResults(index)}>
        <a href="#">{index}</a>
    </li>
)
Andy Ray
  • 30,372
  • 14
  • 101
  • 138