首页 > 解决方案 > 为什么用户在刷新页面后退出?反应/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;
  }
}

用户登录时服务器的响应: 在此处输入图像描述

标签: javascriptreactjsauthenticationredux

解决方案


我真的不知道您如何检查是否有登录用户,但是当您刷新页面时,商店不会自动填充。因此,如果您检查身份验证状态,也许您应该添加类似的内容isAuthenticated

const initialState = {
   token: localStorage.getItem('token'),
   isAuthenticated: localStorage.getItem('token') ? true : false, // or just !!localStorage.getItem('token')
   isLoading: false,
   isRegistered: false
}

或使用某些功能来检查 localStorage 并相应地更新存储。


推荐阅读