我不明白这部分代码:
this.setState({ usernameValid, errorMsg }, this.validateForm);
如果我们正在更新usernameValid
,errorMsg
状态,会this.validateForm
做什么?因为我们是在setState
.
我的代码:
class StandardForm extends Component {
state = {
username: "",
usernameValid: false,
email: "",
emailValid: false,
password: "",
passwordValid: false,
passwordConfirm: "",
passwordConfirmValid: false,
formValid: false,
errorMsg: {},
};
validateForm = () =>{
let { usernameValid, emailValid, passwordValid, passwordConfirmValid} = this.state;
this.setState({
formValid: usernameValid && emailValid && passwordValid && passwordConfirmValid
})
}
validateUsername = () => {
const { username } = this.state;
let usernameValid = true;
let errorMsg = { ...this.state.errorMsg };
if (username.length < 6 || username.length > 16) {
usernameValid = false;
errorMsg.username = "Username should be between 6 and 15 characters";
}
this.setState({ usernameValid, errorMsg }, this.validateForm);
};
validateEmail = () => {
const { email } = this.state;
let emailValid = true;
let errorMsg = { ...this.state.errorMsg };
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
emailValid = false;
errorMsg.email = "Invalid email format";
}
this.setState({ emailValid, errorMsg }, this.validateForm);
};
validatePassword = () =>{
const { password } = this.state;
let passwordValid = true;
let errorMsg = {...this.state.errorMsg}
if(password.length < 8){
let passwordValid = false;
errorMsg.password = "Password should have at least 8 characters"
}
this.state({passwordValid, errorMsg})
}
confirmPassword = () =>{
const { confirmPassword, password } = this.state.confirmPassword
let passwordConfirmValid = true;
let errorMsg = {...this.state.errorMsg}
if(password !== confirmPassword){
let passwordConfirmValid = false;
errorMsg.passwordConfirm = "Password do not match"
}
this.state({passwordConfirmValid, errorMsg})
}