Redux Persist 部分模块持久化存储:代码示例和 TS 类型

本文将介绍如何使用 Redux Persist 对 Redux 仓库的部分模块进行持久化存储,并提供相应的代码示例和 TypeScript 类型定义。

代码示例:

import { combineReducers, configureStore } from '@reduxjs/toolkit'
import { persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import thunk from 'redux-thunk'

// 创建的reducer
import counter from './modules/user'
const persistedModules = ['counter']

// 创建一个新的reducer,只持久化存储指定的模块
const rootReducer: any = (state: any, action: { type: string }) => {
  if (persistedModules.includes(action.type)) {
    return persistedReducer(state, action);
  }
  return state;
};

// 创建persistedReducer,只持久化存储指定的模块
const persistedReducer = persistReducer(
  {
    key: 'root',
    storage,
    whitelist: persistedModules,
  },
  rootReducer
);

const store = configureStore({
  reducer: { persistedReducer },
  devTools: process.env.NODE_ENV !== 'production',
  middleware: [thunk],
})

export default store

TS 类型:

import { Store } from 'redux';
import { Persistor } from 'redux-persist';

interface RootState {
  persistedReducer: any;
}

const store: Store<RootState> & { persistor: Persistor } = configureStore({
  reducer: { persistedReducer },
  devTools: process.env.NODE_ENV !== 'production',
  middleware: [thunk],
});

export default store;

说明:

  1. 使用 persistReducer 创建一个新的 reducer,它会将指定模块的状态持久化存储到本地存储中。
  2. whitelist 属性用于指定需要持久化的模块名称,在本例中为 counter 模块。
  3. rootReducer 是一个新的 reducer,它负责处理所有模块的状态更新,并根据 persistedModules 数组中的模块名称决定是否使用 persistedReducer 来更新状态。
  4. 通过 configureStore 创建 Redux 仓库,并将 persistedReducer 作为 reducer 传入。
  5. 使用 Store<RootState>{ persistor: Persistor } 来扩展 store 类型,以便于访问 persistor 对象。

总结

本文介绍了如何使用 Redux Persist 对 Redux 仓库的部分模块进行持久化存储,并提供了相应的代码示例和 TypeScript 类型定义。希望本文能够帮助您更好地理解和应用 Redux Persist 在项目中的使用。

Redux Persist 部分模块持久化存储:代码示例和 TS 类型

原文地址: https://www.cveoy.top/t/topic/qA4X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录