您现在的位置是:首页 > 文章详情

React中,报错"Cannot read property 'setState' of undefined"时,如何处理

日期:2018-10-24点击:734

 

 App.js 

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props){
        super(props);
        this.state = {
            num: 90
        }         
    };
    handleClick(){
        this.setState({
            num: this.state.num + 1
        })
    };
  render() {
    return (
      <div className="App">
       {this.state.num}
             <button onClick={this.handleClick}>点击</button>
      </div>
    );
  }
}

export default App;

 

我们把num初始值通过构造函数constructor保存在this.state里,之后我们给button按钮一个点击事件handleClick,

然后通过点击button按钮来更新num的初始值,当我们点击的时候,毫无疑问报错了“Cannot read property 'setState' of undefined”,

翻译意思是:‘无法读取未定义的属性'setState'’,他的意思就是告诉我们,当我们点击的时候,并没有读取到setState中的值,也就是说:

handleClick方法中的this与组件中的this不一致,不是同一个this。

碰到这个问题有两种解决方法:这两种方法的目的就是要保证:handleClick方法中的this与组件中的this要保持一致,这样才能读取到setState中的值来改变num,

第一种方法: 

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props){
        super(props);
        this.state = {
            num: 90
        }

        this.handleClick = this.handleClick.bind(this);   //把组件中的this绑定到handleClick方法中,这样就会保持this一致          
    };
    handleClick(){
        this.setState({
            num: this.state.num + 1
        })
    };
  render() {
    return (
      <div className="App">
       {this.state.num}
             <button onClick={this.handleClick}>点击</button>

            <button onClick={this.handleClick.bind(this)}>点击</button> //把上面的写到这里也是可以的
      </div>
    );
  }
}

export default App;

 

第二中方法:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props){
        super(props);
        this.state = {
            num: 90
        }   
    };

 handleClick(){
        this.setState({
            num: this.state.num + 1
        })
    };
   handleClick = () => { //利用箭头函数
        this.setState({
            num: this.state.num + 1
        })
    };
  render() {
    return (
      <div className="App">
       {this.state.num}
             <button onClick={this.handleClick}>点击</button>

            <button onClick={()=> {this.handleClick()}>点击</button>或 <button onClick={() => this.handleClick()}>点击</button>
      </div>
    );
  }
}

export default App;

 

在 React 里面,要将类的原型方法通过 props 传给子组件,传统写法需要 bind(this),否则方法执行时 this 会找不到:

<button onClick={this.handleClick.bind(this)}></button>

或者

<button onClick={() => this.handleClick()}></button>

 

原文链接:https://my.oschina.net/u/3946362/blog/2251944
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章