带有redux-thunk的同步操作

问题描述 投票:0回答:1

对于我的React Web App,我想在访问受保护的链接时检查身份验证令牌。这是检查auth的操作:

export const checkAuthState = () => {
    return (dispatch) => {
        dispatch(loadingStart());
        const eAuth = localStorage.getItem('eAuth');
        if (!eAuth) {
            dispatch(logout());
        } else {
            const employeeData = JSON.parse(localStorage.getItem('employeeData'));
            dispatch(authSuccess(employeeData, eAuth));
        }
    };
};

但是,由于异步运行,reducer中的eAuth状态为null。因此,用户被重定向到登录页面。有没有办法等到eAuth设置后再重定向。我尝试将loading状态添加到true,直到authSuccess将其设置为false,但它也不起作用。

reactjs redux react-redux redux-thunk
1个回答
0
投票

希望它会帮助您,谢谢

export const checkAuthState = () => {
    return async (dispatch) => {
        dispatch(loadingStart());
        const eAuth = await localStorage.getItem('eAuth');
        if (!eAuth) {
            dispatch(logout());
        } else {
            const employeeData = await JSON.parse(localStorage.getItem('employeeData'));
            dispatch(authSuccess(employeeData, eAuth));
        }
    };
};
© www.soinside.com 2019 - 2024. All rights reserved.