javascript 如何在Redux状态下保持黑暗模式

vuv7lop3  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(117)

我用Redux-Toolkit(RTK)Query写了一个主题转换器,但是我找不到一种方法让页面保持刷新前的主题。
代码如下:

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

export const themeSlice = createSlice({
  name: "themeSlice",
  initialState: true, // Initial value is light theme
  reducers: {
    toggleTheme: (state) =>{
      return state = !state; // Changes the theme to dark
    }
  }
});

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

字符串
Redux商店:

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

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


我个人想在localStorage中保存主题名,我试了几个教程,但都不起作用。

gopyfrb3

gopyfrb31#

一个简单的解决方案是从localStorage本地设置初始状态值,并将状态更改持久化到localStorage。
范例:

// Read initial state value from localStorage or provide 
// default fallback value
const initialState = JSON.parse(localStorage.getItem("theme")) ?? true;

export const themeSlice = createSlice({
  name: "themeSlice",
  initialState,
  reducers: {
    toggleTheme: (state) => {
      // Compute the next state
      const nextState = !state;

      // Persist the next state value
      localStorage.setItem("theme", JSON.stringify(nextState));

      // Return the next state value
      return nextState;
    }
  }
});

字符串
x1c 0d1x的数据
Reducer函数应该是纯函数,例如没有副作用,所以上面的解决方案可能会令人皱眉。Redux-Persist是一个常见的和流行的库解决方案,用于持久化和水合Redux存储。如果你已经相当熟悉Redux,那么它大约是5-15分钟的集成。
基本示例:

import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

const persistConfig = {
  key: 'root',
  storage,
};

const rootReducer = combineReducers({
  theme: themeReducer,
});

const persistedReducer = persistReducer(persistConfig, rootReducer)

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

export const persistor = persistStore(store);
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { store, persistor } from "../path/to/store";

...

<Provider store={store}>
  <PersistGate loading={null} persistor={persistor}>
    <App />
  </PersistGate>
</Provider>

的数据


相关问题