Next.js 从 SSG 中的服务器获取 HOC 中的数据

Duy*_*nor 15 static get server-side-rendering higher-order-components next.js

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

例子 :

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>
            )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是在新版本的 Next.js 中,使用 SSG,我无法或我没有找到使用getStaticPropsgetServerSideProps在 HOC 组件中的方法。如果我getInitialProps在 HOC(布局)中使用,我将无法使用getStaticPropsgetServerSideProps在 child 中使用。
那么,如何在 HOC 组件和页面中使用getStaticPropsgetServerSideProps获取数据并进行预渲染?
谢谢。

jul*_*ves 3

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

您可以将 React 组件部分保留在 HOC 中withLayout

// 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>
            );
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

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

// 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);
    };
}
Run Code Online (Sandbox Code Playgroud)

然后可以在导出函数的页面组件中按如下方式使用它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);
Run Code Online (Sandbox Code Playgroud)

相同的方法可用于getStaticProps.