Why does React not allow you to bind an event to a function?

时间:2015-11-12 11:10:53

标签: reactjs

My code below gives me the error similar to this question:

"Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state."

class BookList extends React.Component
{
    removeBook(bookName)
    {
        Actions.UpdateBooks();
    }

    render()
    {
        return (
            <TextField defaultValue={this.book.name}  />
            <i  onClick={this.removeBook(this.book.name)} />
        );
    }
}   

Makes sense - the function is called every time render occurs.

So I changed the binding to

onClick={function() {this.removeBook(book.name);}

and now the method is never called when I click. Why?

2 个答案:

答案 0 :(得分:2)

You should use .bind, because now you call function

this.removeBook.bind(this, book.name);

about second case

onClick={function() {this.removeBook(book.name);}

this in this case will be window in window there is not function removeBook that's why you don't get any result(window.removeBook === undefined)., if you use ES6 you can use arrow function

onClick={() => this.removeBook(book.name) } 

in this case this refers to parent scope

答案 1 :(得分:1)

You're using es6 classes, so automatic binding isn't working: You could use arrow functions (w/ lexical this) like so:

<i onClick={() => this.removeBook(this.book.name)} />