else 语句在反应中被忽略

else statement is ignored in react

当我尝试执行此任务以更改密码时,如果响应为 200,则一切正常,并且还会弹出 window,但如果不是,则不执行 else 语句,它与众不同。完全忽略了。

这是代码

const submitForm = () => {

    let form_data = new FormData();
    form_data.append('old_password', formValues.oldpass);
    form_data.append('new_password', formValues.newpass);
    try {
        axios.put(baseUrl + '/change-password/', form_data,
            {
                headers: {
                    'Authorization': `Token ${token}`
                }
            }


        ).then((response) => {
            const Swal = require('sweetalert2');
            console.log(response.data);
            if (response.status === 200) {

                Swal.fire(
                    'Great!',
                    'Password updated successfully',
                    'success'
                )
            }
            else {
                alert('error ', 'password has not been changed !!');
            }

        });
    } catch (error) {
        console.log(error);

    }
};

请帮助我,我是新手,我已经遇到这个问题好几天了。

如果状态代码不是 2xx,Axios 将抛出响应。这意味着如果你得到例如4xx 或 5xx then 子句不是 运行。相反,您需要一个 catch 子句来处理这种情况。

.then((response) => {
    const Swal = require('sweetalert2');
    console.log(response.data);
    Swal.fire('Great!', 'Password updated successfully', 'success')
}).catch((response) => {
    alert('error ', 'password has not been changed !!');
    console.log(error);
});

在这种情况下,您可以删除 try-catch,因为它不会捕获任何错误。

您可以选择 await axios 调用的结果让当前的 catch 子句捕获错误。然后你还需要函数是 async.

const submitForm = async () => {
    let form_data = new FormData();
    form_data.append('old_password', formValues.oldpass);
    form_data.append('new_password', formValues.newpass);
    try {
        await axios.put(baseUrl + '/change-password/', form_data,
            {
                headers: {
                    'Authorization': `Token ${token}`
                }
            }
        ).then((response) => {
            const Swal = require('sweetalert2');
            console.log(response.data);
            Swal.fire('Great!', 'Password updated successfully', 'success')
        });
    } catch (error) {
        console.log(error);
        alert('error ', 'password has not been changed !!');
    }
};

https://axios-http.com/docs/handling_errors