Setstate Automatically Calling Another Method In React
Solution 1:
In your render method change the buttononClick to something like below
<td><buttononClick={() => this.handleExpenseDelete(index)}>Delete</button></td>You are calling the method while rendering. The above code will call it only onClick.
EDIT:
When the below code is in place, the method(handleExpenseDelete) gets executed during render. Since {} braces indicates the expression inside it has to be executed, the expression inside is to call the function.
onClick={this.handleExpenseDelete(index)}
When you do it this way the expression inside {} is executed which results in a function and this function gets called when you click the button.
onClick={() => this.handleExpenseDelete(index)}
Solution 2:
Reason is, onClick expect a function and you are returning a value by calling that function by onClick={this.handleExpenseDelete(index)}, its a function calling, handleExpenseDelete will get called on each rendering instead of on specific event.
You need to write it like this:
onClick={() => this.handleExpenseDelete(index)}
Or use .bind() and remove the binding from constructor, like this:
onClick={this.handleExpenseDelete.bind(this, index)}
Post a Comment for "Setstate Automatically Calling Another Method In React"