我正在尝试在 React 中使用 setState [英] I am attempting to use setState in React

查看:50
本文介绍了我正在尝试在 React 中使用 setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 setState 函数用于我的 App 类中的方法..

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

当前代码示例:

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

}

我希望我的联系人数组的长度从 5 更改为 6.

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

我收到的错误如下:

TypeError: 无法读取未定义的属性setState"addRandomContact

TypeError: Cannot read property 'setState' of undefined addRandomContact

推荐答案

"this" 关键字将无法在此函数内访问,因此未定义.您必须使用如下箭头函数:

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

这篇关于我正在尝试在 React 中使用 setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆