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.
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>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With