关于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 “Cannot read property 'setState' of null” 的错误
- 关于JS出现的Cannot read property 'XXX' of null错误
- react native与webview通信跳转页面报错:Cannot read property 'setNativeProps' of undefiend
- 关于"Uncaught TypeError: Cannot read property 'time' of null"的处理
- 调用百度报Cannot read property 'lng' of null错误
- 关于js Uncaught TypeError: Cannot read property 'style' of null 问题
- 日常-关于“Cannot read property 'length' of null”报错
- 关于Uncaught TypeError: Cannot set property 'onClick' of null。的问题
- Cannot set property ‘innerHTML’ of null 错误原因
- Cannot set property ‘innerHTML’ of null 错误原因
- 关于JS出现的Cannot read property 'XXX' of null错误
- Uncaught TypeError: Cannot set property ' ' of null 错误解决
- canvas出现Uncaught TypeError: Cannot read property 'getContext' of null 错误
- 在使用renderTo中遇到的Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null
- Pansoft 启动成功但是登录时提示 Cannot read property 'charCodeAt' of null
- Cannot read property ‘msie’ of undefined错误原因以及解决方案
- nodejs async库使用错误: cannot read property 'xxx' of undefined
- cocos2d-js-----Uncaught TypeError: Cannot read property 'style' of null
- easyui:Cannot read property 'nodeName' of null问题的解决
- discuz 出现了Uncaught TypeError: Cannot read property 'appendChild' of null