我想在React中检查Re-password的验证,我为此编写了这段代码但是当你设置(例如)密码:“1234”和重新密码:“1234”它不适用于true但是当您输入重新密码的第五个字符时,它变为True。 你知道什么是问题吗?
import React , { Component } from 'react';
export default class RegistrationForm extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
email:'',
password :'',
password_re:'',
password_has_error:false
};
}
checkPassword() {
if(!this.state.password || this.state.password != this.state.password_re) {
this.setState({password_has_error:true});
}
else {
this.setState({password_has_error:false});
}
}
handleChange(event) {
this.setState({[event.target.name] : event.target.value });
if (event.target.name == 'password' || event.target.name == 'password_re')
this.checkPassword();
}
handleSubmit(event) {
event.preventDefault();
// TODO: will submit the form here
}
render(){
return (
<form onSubmit={(event)=>this.handleSubmit(event)}>
<div>
<label>Name</label>
<input
type="text"
name="name"
value={this.state.name}
onChange={(event)=>this.handleChange(event)}
/>
</div>
<div>
<label>Email address</label>
<input
name="email"
type="email"
value={this.state.email}
onChange={(event)=>this.handleChange(event)}
/>
</div>
<div>
<label>Password</label>
<input
type="password"
name="password"
value={this.state.password}
onChange={(event)=>this.handleChange(event)}
/>
</div>
<div>
<label>Re-enter password</label>
<input
type="password"
name="password_re"
value={this.state.password_re}
onChange={(event)=>this.handleChange(event)}
/>
</div>
<button type="submit">Submit</button>
</form>
)
}
}
编辑:这是我的React组件
答案 0 :(得分:1)
这是因为,setState是异步的,它不会立即更新状态值。
使用setState回调方法这样写:
handleChange(event) {
const { name, value } = e.target
this.setState({
[name] : value
}, () => {
if (name == 'password' || name == 'password_re')
this.checkPassword();
}
}
);
}
检查此项以获取有关setState async behaviour。
的更多详细信息