React 项目中使用 Redux-persist 持久化存储优化 - 如何选择性存储模块
这段代码是在 React 项目中创建一个 Redux store,并使用了 redux-persist 来持久化存储 state。
首先,通过调用 'configureStore' 函数创建一个 Redux store,该函数接受一个配置对象作为参数。在配置对象中,'reducer' 指定了要使用的 reducer(在这里是 'persistedReducer'),'devTools' 用于指定是否在开发环境中启用 Redux DevTools 扩展,'middleware' 列出了要使用的中间件(在这里是 'thunk')。
'persistedReducer' 是一个经过 redux-persist 处理后的 reducer,它会自动将 state 保存到本地存储,并在应用启动时从本地存储中恢复 state。
最新优化是指只有三个模块需要被持久化存储,而另一个模块不需要存储。为了实现这个优化,可以使用 redux-persist 的 'persistReducer' 函数来创建一个新的 reducer,该 reducer 只会将指定的模块进行存储。
以下是示例代码:
import { configureStore } from '@reduxjs/toolkit';
import { persistReducer, persistStore } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import thunk from 'redux-thunk';
// 定义需要持久化存储的模块
const persistedModules = ['module1', 'module2', 'module3'];
// 创建一个新的 reducer,只持久化存储指定的模块
const rootReducer = (state, action) => {
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],
});
const persistor = persistStore(store);
export { store, persistor };
在上述代码中,我们定义了一个数组 'persistedModules' 来存储需要持久化存储的模块的名称。然后,在 'rootReducer' 中,我们检查每个 action 的类型,如果类型在 'persistedModules' 数组中,则使用 'persistedReducer' 来处理该 action。最后,我们使用 'persistReducer' 函数来创建一个新的 reducer,指定 'whitelist' 选项为 'persistedModules' 数组,这样只有这些模块会被持久化存储。
希望以上解释和示例代码对您有所帮助!
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qA3Z 著作权归作者所有。请勿转载和采集!