React - uncaught TypeError:无法读取undefined的属性'setState' [英] React - uncaught TypeError: Cannot read property 'setState' of undefined
本文介绍了React - uncaught TypeError:无法读取undefined的属性'setState'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到以下错误
未捕获的TypeError:无法读取未定义的属性'setState'
Uncaught TypeError: Cannot read property 'setState' of undefined
甚至在构造函数中绑定delta之后。
even after binding delta in the constructor.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta.bind(this);
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}
推荐答案
这是由于 this.delta
没有被绑定到这个
。
This is due to this.delta
not being bound to this
.
为了在构造函数中绑定set this.delta = this.delta.bind(this)
:
In order to bind set this.delta = this.delta.bind(this)
in the constructor:
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta = this.delta.bind(this);
}
目前,您正在调用bind。但是bind返回一个绑定函数。您需要将函数设置为其绑定值。
Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value.
这篇关于React - uncaught TypeError:无法读取undefined的属性'setState'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文