rtk: redux-persist 数据持久化
一个 redux 的中间件,用于存储数据到 localStorage 中
安装
npm install redux-persist
configStore
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import counter from './features/counter.ts';
import projectCompare from './features/project/project-compare.ts'; // defaults to localStorage for web
import todo from './features/todo.ts';
// https://github.com/priteshk191/react-redux-slice-setup/blob/main/src/Redux/store.js
const rootReducer = combineReducers({
counter,
projectCompare,
todo
});
const persistConfigLocal = {
key: 'root',
storage,
whitelist: ['projectCompare']
};
const localPersistedReducer = persistReducer(persistConfigLocal, rootReducer);
const store = configureStore({
reducer: persistReducer(persistConfigSession, localPersistedReducer),
middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: false }),
devTools: false
});
const persistor = persistStore(store);
export { store, persistor };
配置App
import ReactDOM from 'react-dom/client';
import { PersistGate } from 'redux-persist/integration/react';
import App from './app';
import { store, persistor } from './redux-config';
import { Provider } from 'react-redux';
ReactDOM.createRoot(document.getElementById('root')!).render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>
);
配置
防止报错,其实是提示
warning
export const store = configureStore({
reducer: persistingReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
// need to add unnecessary action in a list for avoiding
// errors and warning
ignoredActions: [PERSIST, FLUSH, REHYDRATE, PAUSE, PURGE, REGISTER]
}
})
});