【问题标题】:Why user is logging out after refresh the page? React/Redux app为什么用户在刷新页面后退出?反应/Redux 应用程序
【发布时间】:2020-06-30 14:15:47
【问题描述】:

如标题所示 - 当我在 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;
  }
}

用户登录时服务器的响应:

【问题讨论】:

  • 您也应该在使用 reducers 操作时共享,也许您的持久性代码无法正常工作。或者,您可能对某个操作做出了错误的调用。

标签: javascript reactjs authentication redux


【解决方案1】:

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

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

或使用一些函数来检查 localStorage 并相应地更新存储。

【讨论】:

  • 很高兴它帮助了你! :-)
  • 就是这样!
【解决方案2】:

这里只是猜测,但您的initialState.isAuthenticated 似乎始终是null,您需要根据localStorage 中的token 进行验证

【讨论】:

    【解决方案3】:

    Martial Anouman 的做法是正确的,但从长远来看,我认为您也可以将 redux store 保存到 localStorage,因此如果用户刷新页面,redux 状态将保存到localStorage 和初始状态值在刷新后不会消失。我用redux-persist库,你可以take a look at their github来实现

    【讨论】:

    • 谢谢,我会检查这个解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 2019-03-07
    相关资源
    最近更新 更多