React Redux Store 优化:使用 configureStore 和 Redux Persist 实现数据持久化
这段代码是在 React 项目中创建一个 Redux store,并使用了一个中间件 thunk 来处理异步操作。其中,store 的配置包括了一个 reducer(在这段代码中使用了一个名为 persistedReducer 的 reducer),一个开发工具(在开发环境中启用),和一个中间件(thunk)。
最新的优化是将配置选项作为一个对象传递给 configureStore 函数,而不是将它们作为独立的参数传递。这样做可以更清晰地指定每个选项的含义,并且在未来添加更多选项时更易于扩展。
下面是优化后的代码示例:
const store = configureStore({
reducer: persistedReducer,
devTools: {
enabled: process.env.NODE_ENV !== 'production',
},
middleware: [thunk],
});
对于需要存储的模块,可以使用 Redux Persist 库来持久化存储数据。这个库可以将 Redux store 中的数据保存到本地存储中,以便在刷新页面或重新加载应用程序时保持数据的状态。
下面是一个使用 Redux Persist 的示例:
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
const persistConfig = {
key: 'root',
storage,
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
reducer: persistedReducer,
devTools: {
enabled: process.env.NODE_ENV !== 'production',
},
middleware: [thunk],
});
const persistor = persistStore(store);
export { store, persistor };
在不需要存储的模块中,可以直接使用 configureStore 函数创建一个简单的 store。例如:
const store = configureStore({
reducer: rootReducer,
devTools: {
enabled: process.env.NODE_ENV !== 'production',
},
middleware: [thunk],
});
export { store };
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qA3T 著作权归作者所有。请勿转载和采集!