In this tutorial he uses an onClick function with bind.
<Card onClick={that.deletePerson.bind(null, person)} name={person.name}></Card>
When I remove the bind like this
<Card onClick={that.deletePerson(person)} name={person.name}></Card>
I get an error
Uncaught Error: Invariant Violation: setState(...): Cannot update during an existing state transition (such as within
render
). Render methods should be a pure function of props and state.
I know what bind
does, but why is it needed here? Is the onClick
not calling the function directly?
(code is in this JSbin: )
In this tutorial he uses an onClick function with bind.
<Card onClick={that.deletePerson.bind(null, person)} name={person.name}></Card>
When I remove the bind like this
<Card onClick={that.deletePerson(person)} name={person.name}></Card>
I get an error
Uncaught Error: Invariant Violation: setState(...): Cannot update during an existing state transition (such as within
render
). Render methods should be a pure function of props and state.
I know what bind
does, but why is it needed here? Is the onClick
not calling the function directly?
(code is in this JSbin: https://jsbin./gutiwu/1/edit)
Share Improve this question asked Apr 7, 2015 at 15:31 ilyoilyo 36.4k46 gold badges108 silver badges161 bronze badges 01 Answer
Reset to default 7He's using the bind
so that the deletePerson
method gets the correct person
argument.
Because the Card
ponent doesn't get a full Person
object, this allows him to identify which person's card was actually clicked.
In your example, where you removed the bind onClick={that.deletePerson(person)}
is actually evaluating the function that.deletePerson(person)
and setting that as onClick. The deletePerson
method changes the Component's state, which is what the error message is saying. (You can't change state during a render).
A better solution might be to pass the id into Card, and pass it back up to the app ponent on a delete click.
var Card = React.createClass({
handleClick: function() {
this.props.onClick(this.props.id)
}
render: function () {
return (
<div>
<h2>{this.props.name}</h2>
<img src={this.props.avatar} alt=""/>
<div></div>
<button onClick={this.handleClick}>Delete Me</button>
</div>
)
}
})
var App = React.createClass({
deletePerson: function (id) {
//Delete person using id
},
render: function () {
var that = this;
return (
<div>
{this.state.people.map(function (person) {
return (
<Card onClick={that.deletePerson} name={person.name} avatar={person.avatar} id={person.id}></Card>
)
}, this)}
</div>
)
}
})