我已经在 next js 中使用 next-redux-wrapper 成功实现了 redux-persist
Posted
技术标签:
【中文标题】我已经在 next js 中使用 next-redux-wrapper 成功实现了 redux-persist【英文标题】:I have successfully implemented the redux-persist with next-redux-wrapper in next js 【发布时间】:2021-10-05 03:04:39 【问题描述】:我从外部 api 获取数据并将其存储在 reducer 中。我使用 redux-persist 来保持状态,同时从一个页面导航到另一个页面。但我已经将 whiteList 设为空数组,但所有状态正在坚持吗?需要帮助
import "../assets/css/style.scss";
import "owl.carousel/dist/assets/owl.carousel.css";
import "owl.carousel/dist/assets/owl.theme.default.css";
import Layout from "../component/Layout/Layout";
import wrapper from "../redux/store";
import useEffect from "react";
import useStore from "react-redux";
function MyApp( Component, pageProps )
const store = useStore((store) => store);
useEffect(() =>
typeof document !== undefined
? require("bootstrap/dist/js/bootstrap.bundle")
: null;
, []);
return (
<Layout>
<Component ...pageProps />;
</Layout>
);
export default wrapper.withRedux(MyApp);
import createStore, applyMiddleware from "redux";
import thunk from "redux-thunk";
import composeWithDevTools from "redux-devtools-extension";
import persistStore, persistReducer from "redux-persist";
import storage from "redux-persist/lib/storage";
import rootReducer from "./index";
import createWrapper, HYDRATE from "next-redux-wrapper";
const middleware = [thunk];
let initialState=
// BINDING MIDDLEWARE
const bindMiddleware = (middleware) =>
if (process.env.NODE_ENV !== "production")
return composeWithDevTools(applyMiddleware(...middleware));
return applyMiddleware(...middleware);
;
const makeStore = ( isServer ) =>
if (isServer)
//If it's on server side, create a store
return createStore(rootReducer,initialState, bindMiddleware(middleware));
else
//If it's on client side, create a store which will persis
const persistConfig =
key: "root",
storage: storage,
whiteList: [],
;
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStore(persistedReducer,initialState, bindMiddleware(middleware));
store.__persisitor = persistStore(store); // This creates a persistor object & push that
persisted object to .__persistor, so that we can avail the persistability feature
return store;
;
// export an assembled wrapper
export const wrapper = createWrapper(makeStore);
【问题讨论】:
【参考方案1】:如果您将whitelist
保留为空数组,则不会保留任何内容。
您必须在该字符串数组中放入您想要保留的 redux reducers
值。
例子:
const persistConfig =
key: 'root',
storage: storage,
whiteList: ['cart', 'form', 'user'],
;
【讨论】:
以上是关于我已经在 next js 中使用 next-redux-wrapper 成功实现了 redux-persist的主要内容,如果未能解决你的问题,请参考以下文章
如何在 next.js 中覆盖 react-skylight min-height?
如何将 Font Awesome 添加到 Next.js 项目