天道酬勤,学无止境

I am attempting to use setState in React

I'm attempting to use setState function to a method in my App class..

example of the current code:

addRandomContact() {
this.setState({
  actors: contacts.slice(0, 6)
})

}

I am expecting my contacts array to change from a length of 5 to 6.

The error I am receiving is the following:

TypeError: Cannot read property 'setState' of undefined addRandomContact

标签

评论

"this" keyword will not be accessible inside this function and hence its undefined. You have to use arrow function like below:

addRandomContact = () => {
this.setState({
  actors: contacts.slice(0, 6)
})

Though it's not very clear from your given codebase what is the issue but one possible error you could make is that you are not binding addRandomContact inside constructor of that class component. Try to paste the following code in your constructor and check if it solves

this.addRandomContact = this.addRandomContact.bind(this);

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐