带有redux-wrapper的Ne​​xtjs始终处于初始状态的getInitialProps中

时间:2020-01-30 08:30:32

标签: redux next.js

我已按照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麻烦多于其应有的价值。

0 个答案:

没有答案