反应 - 未捕获的类型错误:无法读取未定义的属性“setState" [英] React - uncaught TypeError: Cannot read property 'setState' of undefined

查看:31
本文介绍了反应 - 未捕获的类型错误:无法读取未定义的属性“setState"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误

<块引用>

未捕获的类型错误:无法读取未定义的属性setState"

即使在构造函数中绑定 delta 之后.

class Counter 扩展 React.Component {构造函数(道具){超级(道具);this.state = {数 : 1};this.delta.bind(this);}增量(){this.setState({计数:this.state.count++});}使成为() {返回 (<div><h1>{this.state.count}</h1><button onClick={this.delta}>+</button>

);}}

解决方案

这是由于 this.delta 没有绑定到 this.

为了在构造函数中绑定set this.delta = this.delta.bind(this):

构造函数(道具){超级(道具);this.state = {数 : 1};this.delta = this.delta.bind(this);}

目前,您正在调用 bind.但是 bind 返回一个绑定函数.您需要将函数设置为其绑定值.

I am getting the following error

Uncaught TypeError: Cannot read property 'setState' of undefined

even after binding delta in the constructor.

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}

解决方案

This is due to this.delta not being bound to this.

In order to bind set this.delta = this.delta.bind(this) in the constructor:

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

    this.delta = this.delta.bind(this);
}

Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value.

这篇关于反应 - 未捕获的类型错误:无法读取未定义的属性“setState"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆