TypeError: Cannot read property 'setState' of undefined

相信每一个初学React的同学都差不多遇到过这个错误。

在js中,function中的this代表调用这个函数的object,也就是谁调用这个函数,那么this就指向谁,这个object可以是window,可以使document,也可以是button。
这个特性导致了React中一个常见的的找不到this的问题,且看下面的代码。

import React, {Component} from "react";

class ThisTest extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'zdd',
    }
  }

  handleClick() {
    this.setState({
      name: 'ddz',
    })
  }

  render() {
    return (
      <button onClick={this.handleClick}>hello</button>
    )
  }
}

export default ThisTest;

以上代码运行的时候会出现如下错误:
TypeError: Cannot read property 'setState' of undefined

为啥呢?
我们来分析一下,函数handleClick中有一个this,这个this指向调用该函数的对象,也就是button,button中没有setState这个方法,所以出错了。怎么解决?两个办法:

方法一:将handleClick改为箭头函数,因为箭头函数中的this指向该函数所在的组件,如下:

​
handleClick = () => {
  this.setState({
    name: 'ddz',
  })
};

方法二:用bind函数将调用的函数绑定到组件上,一般我们在constructor中做这个绑定,上面的代码可以变为:

class ThisTest extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'zdd',
    };

    // 添加下面一行。
    this.handleClick = this.handleClick.bind(this);
  }
}

当然网上还有其他方法,比如使用React.createClass来创建组件,这样会自动将this绑定到组件上,但这种创建组件的方法已经不推荐使用了,或者在render函数中绑定this,如下:

<button onClick={this.handleClick.bind(this)}>hello</button>

或者直接将箭头函数写在调用处,如下:

<button onClick={() => this.handleClick}>hello</button>

这两种方法会有轻微的性能问题,因为每次render函数调用时都会重新分配handleClick这个函数。

推荐第一种方法,简单方便,没有副作用。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值