javascript - 为什么 'if' 条件没有在 ajax 调用的 'then' promise 中得到评估?

标签 javascript ajax reactjs callback promise

我有一个 ajax 调用,最后我有一个“then” promise ,其中我可以看到控制台日志在出现错误时返回 false,但在下一行中似乎没有评估 if 条件。

我在下面的代码中将条件注释为“未评估”。

请引用下面的代码:

    authenticate(email, password){
            const encodedEmail = encodeURIComponent(email); 
            console.log(encodedEmail);
            axios.get(`http://localhost:8080/api/users/${encodedEmail}`,{
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    Authorization: 'Basic ' + btoa(email + ":" + password)
                }
            })
            .then(function (response) {
                console.log(response);
                sessionStorage.setItem('isAuthenticated', true);
            })
            .catch(function (error) {
                console.log(error);
                sessionStorage.setItem('isAuthenticated', false);
            }).then(() => {
                console.log(sessionStorage.getItem('isAuthenticated')); //returns true as expected
                !sessionStorage.getItem('isAuthenticated') 
               && this.props.history.push("/"); // not evaluated
            });
        }

        handleLogIn(e){
            e.preventDefault();
            const email = e.target.elements.email.value;
            const password = e.target.elements.password.value;
            this.authenticate(email, password);
            this.props.dispatch(addCredentials({email, password}));
        }

这是我第一次动手做项目,请大家帮忙! 提前致谢。

最佳答案

!sessionStorage.getItem('isAuthenticated') && x只会评估 x如果sessionStorage.getItem('isAuthenticated')评估为 falsy 值(因为您在测试时使用 ! 反转值)。 "true"不是虚假值,而是真实值。

还有第二个问题:sessionStorage值始终是字符串,因此您正在存储 "true""false" , 两者都是真值,不是 truefalse .

还有第三个问题:this在你的决赛中 then处理程序不会引用您期望它引用的内容,您可能想使用箭头函数(或绑定(bind)函数)。更多相关信息:http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback

所以最小的变化版本是:

  1. 转换 "true""false"返回truefalse , 和

  2. 去掉 !根据您的情况

  3. 使用箭头函数(或绑定(bind)函数)。

我还建议实际使用 if , 不使用 &&对于副作用。

例如(注意箭头函数):

.catch((error) => {
    console.log(sessionStorage.getItem('isAuthenticated')); //returns true as expected
    if (sessionStorage.getItem('isAuthenticated') === "true") {
        this.props.history.push("/");
    }
})

但如果这真的是 promise 链的末端,处理它的正确方法就是将它移到您之前的 then 中。处理程序(注意箭头函数):

axios.get(`http://localhost:8080/api/users/${encodedEmail}`,{
    headers: {
        'Access-Control-Allow-Origin': '*',
        Authorization: 'Basic ' + btoa(email + ":" + password)
    }
})
.then((response) => {
    console.log(response);
    sessionStorage.setItem('isAuthenticated', true);
    this.props.history.push("/"); // <==================
})
.catch((error) => { // Doesn't have to be an arrow, but if you relocate any code...
    console.log(error);
    sessionStorage.setItem('isAuthenticated', false);
});

如果你在决赛中还有其他事情要做 then , 不过,我会通过 promise 链传播标志,而不是返回到 sessionStorage为此:

axios.get(`http://localhost:8080/api/users/${encodedEmail}`,{
    headers: {
        'Access-Control-Allow-Origin': '*',
        Authorization: 'Basic ' + btoa(email + ":" + password)
    }
})
.then((response) => {
    console.log(response);
    sessionStorage.setItem('isAuthenticated', true);
    return true;
})
.catch((error) => {
    console.log(error);
    sessionStorage.setItem('isAuthenticated', false);
    return false;
})
.then((isAuthenticated) => {
    if (isAuthenticated) {
        this.props.history.push("/");
    } else {
        // do the other thing...
    }
});

...但实际上将这两个分支放在 then 中更有意义和 catch处理程序(中间示例),而不是传播标志。

关于javascript - 为什么 'if' 条件没有在 ajax 调用的 'then' promise 中得到评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54027421/

相关文章:

javascript - AngularJS动态添加和删除div不起作用

javascript - 动态图像刷新

javascript - 自动点击链接事件

javascript - 使用本地服务器流式传输图像

javascript - 当我实例化一个新类时使用 .call

ajax - CakePHP,找不到助手类 AjaxHelper

ajax - 如何将 url 重定向到另一个

javascript - 什么时候必须在 useReducer 中使用扩展运算符?

node.js - 如何在 React/Node 中创建 'Load More' 功能而不重新渲染整个组件?

javascript - 访问 react 元素的 child