1

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?

1
  • I found that arrow functions and rebinding this as per the answers below still didn't work. I also had to wrap <i> in <span onclick> otherwise React wasn't adding the event to <i>. Commented Nov 12, 2015 at 11:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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)} />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.