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

时间:2018-07-19 17:26:35

标签: javascript reactjs event-handling 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)

3 个答案:

答案 0 :(得分:1)

您也忘记绑定handleSubmit

要做:

this.onUsernameChange = this.onUsernameChange.bind(this);
this.onPasswordChange = this.onPasswordChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);

在构造函数中

答案 1 :(得分:1)

您还可以对函数使用es6格式,这样可以防止每次在构造函数中编写额外的代码来绑定此上下文。例如。

onUsernameChange = event => {
  this.setState({ username: event.target.value });
}

答案 2 :(得分:0)

我需要添加:

this.handleSubmit = this.handleSubmit.bind(this); 

在构造函数中!