javascript - 为什么用户在刷新页面后退出?反应/Redux 应用程序
问题描述
如标题所示 - 当我在 React/Redux 应用程序中重新加载页面时,用户正在注销。我将令牌存储在 localStorage 中,但它不起作用,因此可能有任何错误。用户登录时应存储令牌。注销工作正常。这是我的代码:
auth.js(reducers 目录 - Redux):
import { LOGIN_SUCCESS, LOGIN_FAIL, LOGOUT_SUCCESS, REGISTER_SUCCESS, REGISTER_FAIL } from '../actions/types';
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: null,
isLoading: false,
isRegistered: false
}
export default function(state = initialState, action) {
switch(action.type) {
case REGISTER_SUCCESS:
return {
...state,
...action.payload,
token: null,
isAuthenticated: false,
isLoading: false,
isRegistered: true
}
case LOGIN_SUCCESS:
localStorage.setItem('token', action.payload.token);
return {
...state,
...action.payload,
isAuthenticated: true,
isLoading: false,
}
case LOGIN_FAIL:
case LOGOUT_SUCCESS:
case REGISTER_FAIL:
localStorage.removeItem('token');
return {
...state,
token: null,
isAuthenticated: false,
isLoading: false
}
default:
return state;
}
}
解决方案
我真的不知道您如何检查是否有登录用户,但是当您刷新页面时,商店不会自动填充。因此,如果您检查身份验证状态,也许您应该添加类似的内容isAuthenticated
:
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: localStorage.getItem('token') ? true : false, // or just !!localStorage.getItem('token')
isLoading: false,
isRegistered: false
}
或使用某些功能来检查 localStorage 并相应地更新存储。
推荐阅读
- php - PHP - 无法从 foreach 循环中获取匹配值
- ruby - 传入命名参数时,Rspec测试一直失败
- python - 试图通过仅获取元组中的整数来形成一个从元组解包中获取其大小的数组
- r - 如何在 R 中编写递归 compose 函数?
- ssh - 关于使用 ssh 进行公钥和私钥签名和验证的问题
- python - 如何在 Python 中将两个关联值存储为数组
- node.js - NPM RUN deploy 给出错误消息。RoboFriends 部署脚本失败。“上面可能有额外的注销”
- javascript - 应用程序外的 Cordova 屏幕截图
- python-2.7 - 分配前引用的Python2?
- python - 为什么 Python 中的 plot_trisurf 在不同的数据和平台中没有显示任何图?