无法读取ReactJS(Gatsby)中未定义的属性'状态'

Cannot read property #39;state#39; of undefined in ReactJS (Gatsby)(无法读取ReactJS(Gatsby)中未定义的属性#39;状态#39;)

本文介绍了无法读取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);

在构造函数中

这篇关于无法读取ReactJS(Gatsby)中未定义的属性&#39;状态&#39;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无法读取ReactJS(Gatsby)中未定义的属性&#39;状态&#39;

基础教程推荐