Javascript 未捕获的类型错误:无法在反应中读取 null 的属性“状态”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37279763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'state' of null in react
提问by Cameron Sima
I am trying to implement a simple signup page in react. However, when I try to submit the form, I get signup.js:53 Uncaught TypeError: Cannot read property 'state' of null
我正在尝试在 React 中实现一个简单的注册页面。但是,当我尝试提交表单时,我得到signup.js:53 Uncaught TypeError: Cannot read property 'state' of null
Apparently react is not properly setting the state. Here is the code from the Signup component:
显然反应没有正确设置状态。以下是 Signup 组件中的代码:
import React, { Component } from 'react';
import React, { Component } from '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>
)
}
}
回答by Alexander T.
You should set this
for handleSubmit
as you did for onChange
你应该设定this
为handleSubmit
像你一样的onChange
constructor(props) {
super(props)
this.state = {
username: "",
password1: "",
password2: "",
error: ""
}
this.onChange = this.onChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}