我正在尝试验证使用以下代码钩子的字段:
const validate = async () => {
if (!new ValidateFields().checkIfValidSnn(snn.value))
setSnn({ ...snn, error: "Invalid snn" })
if (!new ValidateFields().checkIfValidPhone(phone.value))
setPhone({ ...phone, error: "Invalid phone number" })
if (!new ValidateFields().checkIfValidEmail(email.value))
setEmail({ ...email, error: "Invalid Email" })
if (country.value.length <= 0)
setCountry({ ...country, error: "Please select a country" })
return [snn, phone, email, country].every(x => x.error == "" && x.value != "")
}
const submit = () => {
validate()
.then(success => {
if (success)
console.log("SUCCESS!")
else
console.log("Failed")
})
}
但问题是,在验证值时,所有更改都没有更改。如何在不再次运行函数的情况下获取正确的值?
setState
调用异步,因此您无法确定当前值。可以将验证状态存储在局部变量中。而且,如果函数不使用await
,则无需将函数标记为async
。
const validate = () => {
let isValid = true;
if (!new ValidateFields().checkIfValidSnn(snn.value)) {
setSnn({ ...snn, error: 'Invalid snn' });
isValid = false;
}
if (!new ValidateFields().checkIfValidPhone(phone.value)) {
setPhone({ ...phone, error: 'Invalid phone number' });
isValid = false;
}
if (!new ValidateFields().checkIfValidEmail(email.value)) {
setEmail({ ...email, error: 'Invalid Email' });
isValid = false;
}
if (country.value.length <= 0) {
setCountry({ ...country, error: 'Please select a country' });
isValid = false;
}
return isValid;
};
const submit = () => {
if (validate()) {
console.log("SUCCESS!")
} else {
console.log("Failed")
}
}