相信很多初学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这个函数。
推荐第一种方法,简单方便,没有副作用。
网友评论