嘿,伙计们,我在nextjs中使用redux-thunk,现在我想在我的应用程序中添加redux-persistent。所以最初我的代码就像
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import reducer from './reducers';
export const makeStore = (initialState, options) => {
return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunk)));
};
现在有人能帮我设置redux-persistent吗?我尝试了一些解决方案,但没有找到
如果您真的需要持久化redux state
,据我所知,有两种选择:首先,你可以按照你的意愿使用react-persist
,就像这个一样
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;
这是本文的链接,其中包含集成&使用现有应用程序中的程序包。
通常,我遵循与redux商店相同的结构。这种整合总是对我有效。所以我希望这也能帮助你。