使用redux-persist和redux thunk

时间:2020-03-31 18:20:31

标签: reactjs redux react-redux next.js redux-persist

伙计们,我正在将redux thunk与nextjs一起使用,现在我想在我的应用程序中添加redux-persist。所以最初我的代码就像

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设置中帮助我吗?我尝试了一些解决方案,但没有解决

2 个答案:

答案 0 :(得分:4)

如果您确实需要坚持使用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;

答案 1 :(得分:1)

这是link of the article的简单但详细的步骤,用于在您现有的应用程序中集成和使用该软件包。

通常,我遵循与redux存储相同的结构。这种集成始终对我有用。因此,我希望这也会对您有所帮助。