簡體   English   中英

為什么用戶在刷新頁面后退出? 反應/Redux 應用程序

[英]Why user is logging out after refresh the page? React/Redux app

如標題所示 - 當我在 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檢查身份驗證 state ,也許您應該添加類似的內容:

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

或使用一些 function 檢查 localStorage 並相應地更新存儲。

只是在這里猜測,但看起來您的initialState.isAuthenticated始終是null ,您需要驗證來自localStoragetoken

The approach of Martial Anouman is true, but for the long term I think you can save redux store to the localStorage as well, so if user refreshes the page, the redux state will be saved to the localStorage and the initial state values will not be刷新后消失了。 我使用redux-persist庫,你可以看看他們的 github的實現

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM