您的位置:首页 > Web前端 > React

关于React “Cannot read property 'setState' of null” 的错误

2016-12-26 22:00 1096 查看

关于React “Cannot read property ‘setState’ of null” 的错误

最近刚跟着阮一峰大神的博客小小学习了一下React,想试着用ES6语法实现一个简单的按钮功能的时候出现了有个困扰了我一下午的错误:



网上搜了好久stackoverflow上也没找到能完全解决问题的方案,最后还是在这里找到了解决方法

原来是ES6中 this 只能在构造函数中使用了,因此this.setState()这个函数也就不能直接调用了。这个新特性的目的暂时我还不清楚原因总之把解决方法记下先:

class OnlyBt extends React.Component {

constructor(props) {
super(props);
/*关键就是这里,把要使用this的函数  在构造函数中用bind方法传入this*/
this.start = this.start.bind(this);
this.ready = this.ready.bind(this);
this.ok = this.ok.bind(this);
this.again = this.again.bind(this);
this.state = {func : this.start, keyWord : keyWords[key]};
}

start() {
key++;
this.setState({func : this.ready, keyWord : keyWords[key]});
}

ready() {
key++;
this.setState({func : this.ok, keyWord : keyWords[key]});
}

ok() {
key++;
this.setState({func : this.again, keyWord : keyWords[key]});
}

again() {
key = 0;
this.setState({func : this.start, keyWord : keyWords[key]});
}

render() {
return (<button className="btn btn-lg btn-default" onClick={this.state.func}>{this.state.keyWord}</button>);
}
}
ReactDOM.render(<OnlyBt />, document.getElementById('content'));


以上,欢迎 我是初学者,欢迎留言讨论
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  react ES6 state