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>
      </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
        })
    };
  render() {
    return (
      <div className="App">
       {this.state.num}
             <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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值