这个问题其实在一年多以前吧,我就搞清楚了,结果已经很久没用react的类组件了,结果现在用了,发现自己忘了为什么要绑定,所以写一下这篇文章做笔记。
这里要清楚javascript
中的this
指向的问题。
例子
class App extends PureComponent {
state = {
count: 1
}
increase() {
this.setState({
count: this.state.count + 1
})
}
render() {
const { count } = this.state
return <div onClick={this.increase}>{count}</div>
}
}
你会发现它报错了。
这是为什么呢?
在进行props传值的时候,你相当于就是把值赋给了那个props,上面的代码与下面的代码一样。
const {count} = this.state;
const {increase} = this;
return <div onClick={increase}>{count}</div>
你看出来了吧。也就说react执行函数的时候,就是执行函数increase(event)
,而不是this.increase(event)
。所以this
指向的是undefined
,非严格模式指向全局对象。
那么官方就提供了以下几种写法。
第一种:强烈推荐
class App extends PureComponent {
state = {
count: 1
}
increase = () => {
this.setState({
count: this.state.count + 1
})
}
render() {
const { count } = this.state
return <div onClick={this.increase}>{count}</div>
}
}
第二种:也不错。
class App extends PureComponent {
state = {
count: 1
}
constructor(props) {
super(props);
this.increase = this.increase.bind(this);
}
increase() {
this.setState({
count: this.state.count + 1
})
}
render() {
const { count } = this.state
return <div onClick={this.increase}>{count}</div>
}
}
第三种:不推荐
每次组件重渲染时都会重新调用bind
返回一个新的函数。
class App extends PureComponent {
state = {
count: 1
}
increase() {
this.setState({
count: this.state.count + 1
})
}
render() {
const { count } = this.state
return <div onClick={this.increase.bind(this)}>{count}</div>
}
}
每天进步一点点,过了一段时间,你就会发现你比之前提高了很多。