对于我的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
,但它也不起作用。
希望它会帮助您,谢谢
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));
}
};
};