如何在 Next.js 中从服务器获取 HOC 中的数据?

2024-03-23

我使用 Next.js 创建了新应用程序9.3.1.

在带有 SSR 的旧应用程序中,我可以使用getInitialProps函数在 HOC 组件中(而不是在页面中),因此我可以从 HOC 组件中的服务器和页面中获取数据。像这样https://gist.github.com/whoisryosuke/d034d3eaa0556e86349fb2634788a7a1 https://gist.github.com/whoisryosuke/d034d3eaa0556e86349fb2634788a7a1

Example:

export default function withLayout(ComposedComponent) {
  return class WithLayout extends Component {
    static async getInitialProps(ctx) {
      console.log("ctxlayout fire");
      const { reduxStore, req } = ctx || {};
      const isServer = !!req;
      reduxStore.dispatch(actions.serverRenderClock(isServer));

      if (isServer)
        await reduxStore.dispatch(navigationActions.getListMenuAction("menu"));
      // Check if Page has a `getInitialProps`; if so, call it.
      const pageProps =
        ComposedComponent.getInitialProps &&
        (await ComposedComponent.getInitialProps(ctx));
      // Return props.
      return { ...pageProps };
    }

    render() {
      return (
        <div className="app__container">
          <Header />
          <Navbar />
          <ComposedComponent {...this.props} />
        </div>
      );
    }
  };
}

但是在带有SSG的Next.js新版本中,我找不到使用方法getStaticProps or getServerSideProps在 HOC 组件中。如果我使用getInitialProps在 HOC(布局)中,我将无法使用getStaticProps or getServerSideProps在孩子。

那么,我该如何使用getStaticProps or getServerSideProps在 HOC 组件和页面中获取数据并预渲染?


Because getServerSideProps/getStaticProps如果需要直接从页面组件的文件中导出,则必须将该逻辑完全提取到单独的高阶函数(HOF)中。

您可以将 React 组件部分保留为原样withLayout HOC.

// hoc/with-layout.js
export default function withLayout(ComposedComponent) {
    return class WithLayout extends Component {
        render() {
            return (
                <div className="app__container">
                    <Header />
                    <Navbar />
                    <ComposedComponent {...this.props} />
                </div>
            );
        }
    };
}

里面的代码getInitialProps将被转移到一个单独的 HOF。本 HOF 将接受getServerSidePropsfunction 作为参数,并返回逻辑所在的另一个函数。

// hoc/with-layout.js
export function withLayoutGSSP(gssp) {
    return async (context) => {
        //Add higher-order function logic here
        
        // Return by calling the passed `getServerSideProps` function
        return await gssp(context);
    };
}

然后可以在导出的页面组件中按如下方式使用它getServerSideProps函数(对于您想要重用 HOC 的任何页面组件,都会执行相同的操作)。

import withLayout, { withLayoutGSSP } from '<path-to>/hoc/with-layout'

const IndexPage = () => {
    // Your page component code
};

export const getServerSideProps = withLayoutGSSP(context => {
    // Your `getServerSideProps` code here
});

export default withLayout(IndexPage);

同样的方法可用于getStaticProps.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Next.js 中从服务器获取 HOC 中的数据? 的相关文章

随机推荐