首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用redux-persist和redux thunk

使用redux-persist和redux thunk
EN

Stack Overflow用户
提问于 2020-04-01 02:20:32
回答 2查看 3.3K关注 0票数 0

嘿,伙计们,我在使用redux thunk和nextjs,现在我想在我的应用程序中添加redux-persist。所以最初我的代码是这样的

代码语言:javascript
复制
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?我试过一些解决方案,但没有解决。

EN

回答 2

Stack Overflow用户

发布于 2020-04-01 09:10:32

如果您确实需要持久化您的redux state,据我所知,有两种选择:首先,您可以根据自己的意愿使用react-persist,如下所示

代码语言:javascript
复制
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中的说明执行以下操作

代码语言:javascript
复制
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

代码语言:javascript
复制
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;
票数 14
EN

Stack Overflow用户

发布于 2020-04-05 19:32:45

这里的link of the article有简单但详细的步骤来集成和使用你现有的应用程序中的包。

通常,我遵循与redux store相同的结构。这种集成对我来说总是有效的。所以我希望这也能帮到你。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60957318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档