如何解决在 Redux 中使用持久化的 NextJS 服务器端渲染
我刚刚开始从单页应用程序迁移到 NextJS。我知道这听起来很奇怪,但是当使用持久器时,服务器端渲染无法正常工作,而是像客户端渲染一样打印。
下面是我的商店文件。
import {createStore,applyMiddleware} from 'redux';
import {createWrapper,HYDRATE} from 'next-redux-wrapper';
import logger from 'redux-logger';
import reducer from '../reducers';
const makeConfiguredStore = (reducer) =>
createStore(reducer,undefined,applyMiddleware(logger));
const makeStore = () => {
const isServer = typeof window === 'undefined';
if (isServer) {
return makeConfiguredStore(reducer);
} else {
// we need it only on client side
const {persistStore,persistReducer} = require('redux-persist');
const storage = require('redux-persist/lib/storage').default;
const persistConfig = {
key: 'nextjs',whitelist: ['user'],// make sure it does not clash with server keys
storage
};
const persistedReducer = persistReducer(persistConfig,reducer);
const store = makeConfiguredStore(persistedReducer);
store.__persistor = persistStore(store); // Nasty hack
return store;
}
};
// export an assembled wrapper
export const wrapper = createWrapper(makeStore,{debug: true});
这是我的 _app.js
import {PersistGate} from 'redux-persist/integration/react';
import {useStore} from 'react-redux'
export default wrapper.withRedux(({Component,pageProps}) => {
// return <>
// <Component {...pageProps} />
// <ToastContainer />
// </>
// --> works fine with ssr,but states not persisting..
const store = useStore();
return (
<PersistGate persistor={store.__persistor}>
<Component {...pageProps} />
<ToastContainer />
</PersistGate>
);
});
当页面加载并更新状态时,刷新浏览器后,状态保持不变,但在页面源(不是 ssr)上看不到。
这将是我在服务器端呈现的最佳方案(尽管不必在服务器端看到状态)并且即使在刷新浏览器后也能保持状态。
这是一种合理的方法吗?还是我违背了 NextJS 的本质?
请分享您的想法!
解决方法
@Sungpah Lee,你在补水吗?
https://github.com/kirill-konshin/next-redux-wrapper#state-reconciliation-during-hydration
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。