反应挂钩值未在异步功能中更新

时间:2020-06-23 14:07:51

标签: reactjs react-hooks

我正在尝试通过以下代码验证使用钩子的字段:

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")
        })
}

但是问题是,到验证结果返回值时,所有更改都不会更改。如何在不再次运行函数的情况下获得正确的值?

1 个答案:

答案 0 :(得分:1)

setState调用异步,所以您不能确定当前值。您可以将验证状态存储在本地变量中。如果您不使用功能async,则无需标记功能await

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")
    }
}