React 报错"Cannot read property 'setState' of undefined"

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>

猜你喜欢

转载自my.oschina.net/u/3946362/blog/2251944