【问题标题】:Uncaught TypeError: Cannot read property 'state' of null in react未捕获的类型错误:无法在反应中读取 null 的属性“状态”
【发布时间】:2016-09-13 18:26:39
【问题描述】:

我正在尝试在 react 中实现一个简单的注册页面。但是,当我尝试提交表单时,我得到signup.js:53 Uncaught TypeError: Cannot read property 'state' of null

显然 react 没有正确设置状态。以下是注册组件的代码:

从'react'导入反应,{组件};

export default class Signup extends Component {

  constructor(props) {
    super(props)
    this.state = {
        username: "",
        password1: "",
        password2: "",
        error: ""
      }
    this.onChange = this.onChange.bind(this);
  }

  onChange(e) {
    this.setState({[e.target.name]: e.target.value})
  }

  handleSubmit(e) {
    e.preventDefault()
    console.log(e)
    var username = this.state.username.trim()
    var password1 = this.state.password1.trim()
    var password2 = this.state.password2.trim()

    if (!username || !password1 || !password2) 
      return
    else if (password2 !== password1)
      this.setState({
        error: "Passwords didn't match",
        username: "",
        password1: "",
        password2: ""
        })
  }
  render() {
    return (
      <div>
        <form className="signupForm" onSubmit={this.handleSubmit}>
          <input
            type="text"
            name="username"
            placeholder="Username"
            value={this.state.username}
            onChange={this.onChange} />
          <input
            type="text"
            name="password1"
            placeholder="Password"
            value={this.state.password1}
            onChange={this.onChange} />
          <input
            type="text"
            name="password2"
            placeholder="Password again"
            value={this.state.password2}
            onChange={this.onChange} />
          <input type="submit" value="Post" />
        </form>
        <div value={this.state.error}></div>
      </div>
      )
  }
}

【问题讨论】:

    标签: javascript node.js reactjs


    【解决方案1】:

    您应该为handleSubmit 设置this,就像为onChange 所做的那样

    constructor(props) {
      super(props)
      this.state = {
        username: "",
        password1: "",
        password2: "",
        error: ""
      }
      this.onChange = this.onChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2022-06-16
      • 2015-08-19
      • 1970-01-01
      • 2021-11-18
      • 2022-11-09
      • 2022-01-01
      相关资源
      最近更新 更多