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

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

问题描述

我不知道我是否在这里遗漏了一些小东西?

只是想了解状态如何与 React 一起工作.

只需创建一个小复选框,即可在选中/取消选中时更改文本.

从'react'导入React;导出默认类 Basic extends React.Component {构造函数(道具){超级(道具);this.state = {检查:正确};}句柄检查(){this.setState = ({检查:!this.state.checked});}使成为() {var msg;如果(this.state.checked){msg = '检查'} 别的 {msg = '未选中'}返回 (<div><input type="checkbox" onChange={this.handleCheck} defaultChecked={this.state.checked}/><h3>复选框是{msg}</h3>

);}}

解决方案

变更:

1. 你忘记绑定 onChange 方法,要么用这个:

onChange={this.handleCheck.bind(this)}

或者在constructor中定义绑定:

this.handleCheck = this.handleCheck.bind(this)

2.您以错误的方式使用了 setState,setState 是您需要调用它的方法.

代替:this.setState = ({})

应该是:this.setState({})

I can not figure out if I am missing something small here?

Just trying to get a grasp on how state works with React.

Just creating a small check box that changes text on check/uncheck.

import React from 'react';

export default class Basic extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            checked: true
        };
    }

    handleCheck() {
        this.setState = ({
            checked: !this.state.checked
        });
    }

    render() {
        var msg;
        if (this.state.checked) {
            msg = 'checked'
        } else {
            msg = 'unchecked'
        }
        return (
            <div>
                <input type="checkbox" onChange={this.handleCheck} defaultChecked={this.state.checked} />
                <h3>Checkbox is {msg}</h3>
            </div>
        );
    }
}

解决方案

Changes:

1. You forgot to bind the onChange method, either use this:

onChange={this.handleCheck.bind(this)}

or define the binding in the constructor:

this.handleCheck = this.handleCheck.bind(this)

2. You used setState in a wrong way, setState is a method you need to call it.

Instead of: this.setState = ({})

it should be: this.setState({})

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

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