Reputation: 75
can someone explain to me please why this code works
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
onClick={() => this.handleClick(i)}
/>
);
}
but if remove the arrow function in the elements onClick value
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
onClick={this.handleClick(i)}
/>
);
}
it gives me the error Warning: Cannot update during an existing state transition (such as within render
). Render methods should be a pure function of props and state.%s
The full code can be found here https://codepen.io/gaearon/pen/KmmrBy?editors=0010
Upvotes: 2
Views: 87
Reputation: 342
onClick
require a function, in the first example, you passed the function (arrow function), but the second example, it's not a function.
another way
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
onClick={function(){
this.handleClick(i)
}}
/>
);
}
Upvotes: 1
Reputation: 2104
If you want to use the second example... You must use an double arrow function.. Because every time you render that component you will execute this.handleClick(i)
that leads you to an infinite execution of that function, to avoid this behavior use the double arrow function:
const handleClick = i => e => {
// do anything with i here ...
}
Upvotes: 1