我已按照next-redux-wrapper
和设置_app.ts
的说明进行操作。
import { NextComponentType } from 'next';
import React from 'react';
import { Provider } from 'react-redux';
import withRedux from 'next-redux-wrapper';
import { initializeStore, AppStore, globalReducer } from '../lib/store';
import { getCookie } from '../utils/cookie';
import { load } from '../lib/actions';
import { composeWithDevTools } from 'redux-devtools-extension';
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const makeStore = (initialState, options) => {
return createStore(
globalReducer,
initialState,
composeWithDevTools(applyMiddleware(thunk))
);
};
function MyApp({
Component,
pageProps,
store,
}: {
Component: NextComponentType;
pageProps: any;
store: AppStore;
}) {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
MyApp.getInitialProps = async ({ Component, ctx }) => {
// we can dispatch from here too
const auth = getCookie('auth', ctx.req);
if (auth && !ctx.store.getState().user) {
await ctx.store.dispatch(load(auth)); //loads the user, etc
}
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
return { pageProps };
};
export default withRedux(makeStore)(MyApp);
几乎所有内容似乎都可以正常工作和连接,但是我注意到当我从ctx .store.getState()
访问getInitialProps
时,似乎总是存储了初始状态。
更糟糕的是,页面闲置时似乎不断在调用getInitialProps
。
任何人都知道发生了什么事吗?
我真的开始觉得nextjs和ssr麻烦多于其应有的价值。