[英]this.setState and this.state problem for Register page
I have a code for Registration Page. 我有一个注册页面代码。 Where I'm trying to send data to database by using this.setState and this.state but everytime I run the code Its showing some error in onSubmit Function about this.state .
我试图使用this.setState和this.state将数据发送到数据库的地方,但是每次我运行代码时,它在onSubmit Function中都显示有关this.state的错误。 Why I'm getting this error please tell me.
为什么我收到此错误,请告诉我。 I've a project to submit and I'm stuck on this
我有一个要提交的项目,我对此很执着
import React, {Component} from 'react';
import {register} from './UserFunctions';
class Register extends Component {
constructor() {
super()
this.state = {
first_name: '',
last_name: '',
email: '',
password: ''
};
this.onChange = this.onChange.bind(this)
this.onChange = this.onChange.bind(this)
}
onChange(e){
this.setState({[e.target.name]: e.target.value});
}
onSubmit(e){
e.preventDefault()
const user = {
first_name: this.state.first_name, [error line]
last_name: this.state.last_name,
email: this.state.email,
password: this.state.password
}
register(user).then(res => {
if (res) {
this.props.history.push('/login');
}
})
}
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-6 mt-5 mx-auto">
<form noValidate onSubmit={this.onSubmit}>
<h1 className="h3 mb-3 font-weight-normal">Please Sign in!</h1>
<div className="form-group">
<label htmlFor="first_name">First Name</label>
<input type="text"
className="form-control"
name="first_name"
placeholder="First Name"
value={this.state.first_name}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="last_name">Last Name</label>
<input type="text"
className="form-control"
name="last_name"
placeholder="Last Name"
value={this.state.last_name}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email Address</label>
<input type="email"
className="form-control"
name="email"
placeholder="Enter Email"
value={this.state.email}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password"
className="form-control"
name="password"
placeholder="Enter Password"
value={this.state.password}
onChange={this.onChange}
/>
</div>
<button type="submit"
className="btn btn-lg btn-primary btn-block">
Register
</button>
</form>
</div>
</div>
</div>
)
}
}
export default Register
Please tell me what should I do to solve this problem. 请告诉我该怎么做才能解决这个问题。
You have to bind it like you did with onChange 您必须像使用onChange一样绑定它
this.onSubmit = this.onSubmit.bind(this)
You forgot to do it probably, when copying onChange. 复制onChange时,您可能忘记了这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.