我收到以下错误
Uncaught TypeError: Cannot read property 'setState' of undefined
即使在构造函数中绑定(bind)了 delta。
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
未绑定(bind)到 this
。
为了在构造函数中绑定(bind)集合this.delta = this.delta.bind(this)
:
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta = this.delta.bind(this);
}
目前,您正在调用绑定(bind)。但是 bind 返回一个绑定(bind)函数。您需要将函数设置为其绑定(bind)值。
关于javascript - react - 未捕获的类型错误 : Cannot read property 'setState' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32317154/