简单的React组件无法读取状态

时间:2019-04-19 22:15:23

标签: javascript reactjs

为了清楚起见,我已经将登录组件简化为以下定义

import React from "react";

export default class LoginComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userName: '',
        };
        this.updateUserName = this.updateUserName.bind(this);
    }

    onClickSignUp() {
        console.log(this.state);
        alert("clicked sign up with value: username=" + this.state.userName);
    }
    updateUserName(e) {
        console.log(e);
        this.setState({
            userName: e.target.value
        });
    }

    render() {
        return (
            <div className="LoginComponent">
                <h1>Welcome!</h1>

                <div className="UserNameSegment">
                    <text>UserName: </text>
                    <input id="UserNameInput" value={this.state.userName} onChange={e => this.updateUserName(e)} />
                </div>

                <div className="ButtonGroup">
                    <button id="SignUpButton" onClick={this.onClickSignUp}>Sign Up</button>
                </div>
            </div>
        );
    }
}

预期的功能是,当我单击“注册”按钮时,它将显示一个警报,通知我输入了输入的用户名。目前,当我输入一些文本并单击“注册”按钮时,应用程序崩溃,并告诉我我尚未定义LoginComponent的状态:Uncaught TypeError: Cannot read property 'state' of undefined。我觉得我已经在构造函数中定义了状态...在某些情况下不会调用构造函数?我在这里想念什么?

2 个答案:

答案 0 :(得分:1)

您在this.onClickSignUp = this.onClickSignUp.bind(this);函数中忘记了此行constructor

答案 1 :(得分:1)

将onClickSignUp更改为:

onClickSignUp = () => {
    console.log(this.state);
    alert("clicked sign up with value: username=" + 
this.state.userName);
}