首页 > 解决方案 > TypeError:无法读取未定义的属性(读取“状态”)reactjs

问题描述

我正在尝试在 reactjs 的 onClick 中控制台记录用户名和密码,但我收到了 TypeError。我在类的构造函数下定义了身份验证函数。下面是完整的代码。有人可以在这里指导我吗?

 authenticate(e){
        e.preventDefault();
        var details = {
            "email" : this.state.username,
            "password" : this.state.password
        }
        alert(details.username + details.password);


 <input type="email" onChange = {(event,newValue) => this.setState({username:newValue})} className="form-control" name="email" placeholder="Enter your Email" required="required" />

<input type="password" onChange = {(event,newValue) => this.setState({password:newValue})} className="form-control" name="password" placeholder="Enter your Password" required="required" />

<button className="btn w-100 mt-3 mt-sm-4" onClick={this.authenticate} type="submit">Sign In</button>

标签: javascripthtmlcssreactjs

解决方案


var details = {
            "email" : this.state.username,
            "password" : this.state.password
        }
        alert(details.username + details.password);

In this right here, you call for details.username but details will only have the keys email and password.

So basically, details.username is undefined, and you can't read that property.

Try changing it to

var details = {
                "email" : this.state.username,
                "password" : this.state.password
            }
            alert(details.email + details.password);

推荐阅读