gpt4 book ai didi

reactjs - 使用 redux-persist 和 redux thunk

转载 作者:行者123 更新时间:2023-12-05 08:15:19 25 4
gpt4 key购买 nike

大家好,我在 nextjs 中使用了 redux thunk,现在我想在我的应用程序中添加 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 persist 的设置中帮助我吗?我尝试了一些解决方案,但没有成功

最佳答案

如果你真的需要保留你的 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 };

然后在您的组件中,按照他们的文档

中的说明执行以下操作
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>
);
};

或者您可以简单地执行以下而不依赖库

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;

关于reactjs - 使用 redux-persist 和 redux thunk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60957318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com