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

如何在Redux-Toolkit中持久化暗黑模式至localStorage

解决RTK主题切换器刷新后状态丢失问题

要实现主题状态持久化到localStorage,有两种实用方案,可根据场景选择:

方案一:手动读写localStorage(无额外依赖)

直接在slice中处理localStorage的读取和写入,适合简单场景:

修改themeSlice代码

import { createSlice } from "@reduxjs/toolkit";

// 从localStorage读取初始状态,不存在则用默认值true(浅色主题)
const initialThemeState = JSON.parse(localStorage.getItem('theme')) ?? true;

export const themeSlice = createSlice({
  name: "themeSlice",
  initialState: initialThemeState,
  reducers: {
    toggleTheme: (state) => {
      const newThemeState = !state;
      // 切换后将新状态保存到localStorage
      localStorage.setItem('theme', JSON.stringify(newThemeState));
      return newThemeState;
    }
  }
});

export const { toggleTheme } = themeSlice.actions
export default themeSlice.reducer;

确保store导入正确

检查store文件,确认已正确导入themeReducer:

import { configureStore } from "@reduxjs/toolkit";
// 替换为你的themeSlice实际路径
import themeReducer from "./themeSlice";

export const store = configureStore({
  reducer: {
    theme: themeReducer,
  },
})

方案二:使用redux-persist(适合多状态持久化场景)

如果后续有更多状态需要持久化,推荐用redux-persist这个常用的持久化库:

1. 安装依赖

npm install redux-persist

2. 配置store

import { configureStore } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // 默认使用localStorage
import themeReducer from './themeSlice';

// 持久化配置
const persistConfig = {
  key: 'theme-root', // 存储的根键名
  storage,
  whitelist: ['theme'] // 仅持久化theme reducer的状态
};

// 创建持久化reducer
const persistedReducer = persistReducer(persistConfig, themeReducer);

export const store = configureStore({
  reducer: {
    theme: persistedReducer,
  },
});

export const persistor = persistStore(store);

3. 根组件包裹PersistGate

在根组件(如App.js或index.js)中用PersistGate包裹应用,确保状态恢复后再渲染:

import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from './store';

function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        {/* 你的应用内容 */}
      </PersistGate>
    </Provider>
  );
}

export default App;

注意事项

  • 组件中使用主题状态时,需根据store值正确切换页面样式(比如给body添加dark类)
  • localStorage存储的是字符串,读写时要使用JSON.parse和JSON.stringify处理布尔值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:36:12