我有一个登录表单。我试图在 React 中验证它。OnSubmit 在表单标签上,它调用handleSubmit()。该函数然后调用调用 validateForm() 的 validateField()。全部看formValid是否为真。当我输入正确的电子邮件和密码格式并单击提交时,它返回错误。我再试一次,结果是假的。
第三次点击提交,表格有效,提交快递。为什么它不能立即识别状态更改以形成有效,我该如何更好地响应验证?
谢谢一堆
import React, { Component } from 'react';
import './resources/Home.css';
import FormErrors from './FormErrors.js';
import { Redirect } from 'react-router-dom';
class Home extends Component {
constructor(props){
super(props)
this.state = {
email: '',
password: '',
formErrors: {email: '', password: ''},
emailValid: false,
passwordValid: false,
formValid: false
};
this.handleSubmit = this.handleSubmit.bind(this);
this.onChange = this.onChange.bind(this);
this.validateField = this.validateField.bind(this);
this.validateForm = this.validateForm.bind(this);
}
onChange(event){
event.preventDefault();
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({[name]: value});
}
validateField() {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
let passwordValid = this.state.passwordValid;
emailValid = this.state.email.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{0,})$/i);
fieldValidationErrors.email = emailValid ? '' : 'email is invalid';
passwordValid = this.state.password.length >= 6;
fieldValidationErrors.password = passwordValid ? '': ' password is too short';
this.setState({formErrors: fieldValidationErrors,
emailValid: emailValid,
passwordValid: passwordValid
}, this.validateForm());
}
validateForm() {
this.setState({formValid: this.state.emailValid && this.state.passwordValid});
}
handleSubmit(event) {
event.preventDefault();
console.log('pressed submit');
console.log('form valid: ' + this.state.formValid);
this.validateField();
if ( this.state.formValid === true) {
console.log('here');
fetch('/login', {
method: 'post',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"email" : this.state.email,
"password" : this.state.password
})
})
.then(response => response.json().then(data => ({status: response.status,data:data})))
.then(res => {
res.status === 200 ? alert('success') : alert('fail')
res.data.errors.map(x => alert(x.msg)) })
}
}
render() {
return (
<div class="page">
<div className="Home">
<div id="formWrap" >
{// <div className="panel panel-default">
// <FormErrors formErrors={this.state.formErrors} />
// </div>
}
<h2>Login</h2>
<form id="sendInfo" onSubmit={this.handleSubmit} >
{this.state.formValid ? '' :this.state.formErrors.email}
<input data-lpignore="true" type="text" placeholder="email" name="em" name="email" value={this.state.email} onChange={this.onChange}/>
{this.state.formValid ? '' : this.state.formErrors.password }
<input data-lpignore="true" type="text" placeholder="password" name="pw" name="password" value={this.state.password} onChange={this.onChange}/>
<input type="submit" id="submit" value="submit"/>
</form>
</div>
</div>
</div>
);
}
}
export default Home;