无法读取ReactJS(Gatsby)中未定义的属性';状态';
我有以下代码:
export default class Contact extends React.Component {
constructor(props) {
super(props);
this.state = {
password: '',
redirect: false,
username: ''
};
this.onUsernameChange = this.onUsernameChange.bind(this);
this.onPasswordChange = this.onPasswordChange.bind(this);
}
onUsernameChange(event) {
this.setState({ username: event.target.value });
}
onPasswordChange(event) {
this.setState({ password: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
alert('A name was submitted: ' + this.state.username);
//sessionStorage.setItem('username', this.state.username);
}
render() {
return (
<div>
<form className="form-signin" onSubmit={this.handleSubmit}>
<input type="text" value={this.username} onChange={this.onUsernameChange} />
<input type="password" value={this.password} onChange={this.onPasswordChange} />
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
提交用户名和密码后:我收到以下错误:
TypeError: Cannot read property 'state' of undefined
在以下行:
alert('A name was submitted: ' + this.state.username);
有什么问题?用户名不保存吗?(我正在使用Gatsby-reactjs)
解决方案
您也忘了绑定handleSubmit
做:
this.onUsernameChange = this.onUsernameChange.bind(this);
this.onPasswordChange = this.onPasswordChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
在构造函数中
相关文章