我正在使用 react redux 实现两种不同类型用户的登录。这是我的登录方法:
export const login = (credentials) => (dispatch) =>
api.user.login(credentials).then(user => {
localStorage.userJWT = user.token;
localStorage.userEmail = user.email;
localStorage.userId = user.id;
localStorage.surname = user.surname;
localStorage.type = user.type;
dispatch(userLoggedIn(user));
});
- 对于第一种类型的用户,我从后端返回:令牌、电子邮件、ID、姓氏。
- 对于第二种类型的用户,我从后端返回:token、email、id、type。
我做了一些第二类用户无法访问的安全路由。因此,如果surname
返回变量,我会为该用户定义特定的路由。
如果type
返回变量,它会正确显示链接和 redux 存储中的所有内容。但是,如果我重新加载页面,它会自动将变量更改type
为undefined surname
.
这是我尝试在商店中保存 redux 状态的地方,即使我重新加载页面。const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)));
if(localStorage.userJWT && localStorage.userEmail && localStorage.userId && localStorage.type){
const user = { token: localStorage.userJWT, email: localStorage.userEmail, id: localStorage.userId, type: localStorage.type};
store.dispatch(userLoggedIn(user));
}
if(localStorage.userJWT && localStorage.userEmail && localStorage.userId && localStorage.surname){
const user = { token: localStorage.userJWT, email: localStorage.userEmail, id: localStorage.userId, surname: localStorage.surname};
store.dispatch(userLoggedIn(user));
}
您能否建议为什么它不遵循我的 if 语句。先感谢您。