You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Redux Toolkit将isAuthenticated持久化到Local Storage的异常问题

问题根源

localStorage 仅支持存储字符串类型数据,你直接读取 localStorage 中的布尔值时,取出的实际是 "true" 或 "false" 字符串,非空字符串转换为布尔值时都会被判定为 true,这就是你状态始终为 true 的核心原因。此外你当前的代码没有在登录/登出状态变更时同步更新 localStorage,也会导致持久化失效。

解决方案

不需要额外引入第三方依赖,直接修改你的 Redux Toolkit 代码即可,修改点如下:

  1. 调整 auth 状态的初始值,正确读取并转换 localStorage 中存储的布尔值
  2. 在 login、logout reducer 触发时同步更新 localStorage 中的状态值

修改后的完整代码:

import { createSlice, configureStore } from '@reduxjs/toolkit';

//MOVEMENTS (doesn't work yet)
const initialMovementsState = {
  movements: [],
};

const movementsSlice = createSlice({
  name: 'movements',
  initialState: initialMovementsState,
  reducers: {
    add(state) {
      //nothing yet
    },
    decrement(state) {
      //nothing yet
    },
  },
});

//LOGGING IN/OUT
const initialAuthState = {
  // 转换localStorage取值为布尔值,无存储值时默认未登录
  isAuthenticated: JSON.parse(localStorage.getItem('isAuthenticated') || 'false'),
};

const authSlice = createSlice({
  name: 'auth',
  initialState: initialAuthState,
  reducers: {
    login(state) {
      state.isAuthenticated = true;
      // 登录时同步更新localStorage
      localStorage.setItem('isAuthenticated', 'true');
    },
    logout(state) {
      state.isAuthenticated = false;
      // 登出时同步更新localStorage,也可使用localStorage.removeItem('isAuthenticated')
      localStorage.setItem('isAuthenticated', 'false');
    },
  },
});

//STORE CONFIGURATION

const store = configureStore({
  reducer: {
    movements: movementsSlice.reducer,
    auth: authSlice.reducer,
  },
});

export const movementsActions = movementsSlice.actions;
export const authActions = authSlice.actions;

export default store;

如果你后续需要持久化更多 Redux 状态字段,可以考虑引入 redux-persist 库实现更完整的持久化逻辑,当前单字段登录状态场景下上述方案足够轻便可用。


内容的提问来源于stack exchange,提问作者Ania Kowalska

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 15:03:03