Если вам действительно нужно сохранить ваш redux state
, насколько я знаю, есть два варианта: сначала вы можете использовать react-persist
в соответствии с вашим sh, как это
import { createStore, applyMiddleware } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import reducer from './reducers';
import storage from 'redux-persist/lib/storage';
const persistConfig = {
key: 'reducer',
storage: storage,
whitelist: ['reducer'] // or blacklist to exclude specific reducers
};
const presistedReducer = persistReducer(persistConfig, reducer );
const store = createStore(presistedReducer,
composeWithDevTools(applyMiddleware(thunk)));
const persistor = persistStore(store);
export { persistor, store };
, а затем в вашем component
вы делаете следующее, как указано в их documentation
import { PersistGate } from 'redux-persist/integration/react';
// ... normal setup, create store and persistor, import components etc.
const App = () => {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<RootComponent />
</PersistGate>
</Provider>
);
};
, или вы можете просто сделать следующее without relying on a library
import {
createStore, combineReducers, compose, applyMiddleware,
} from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers';
function saveToLocalStorage(state) {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
}
function loadFromLocalStorage() {
const serializedState = localStorage.getItem('state');
if (serializedState === null) return undefined;
return JSON.parse(serializedState);
}
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const presistedState = loadFromLocalStorage();
const store = createStore(
reducer,
presistedState,
composeEnhancers(applyMiddleware(thunk)),
);
store.subscribe(() => saveToLocalStorage(store.getState()));
export default store;