首页 文章

next.js全局布局组件中的getInitialProps

提问于
浏览
0

我正在使用next.js Build 一个网站,我试图围绕以下“问题” . 我有一些需要从API endpoints (无头CMS)获取的静态数据(网站文本) .

对于单个页面,我使用 getInitialProps 来获取所需的数据 . 但是我的主布局中也有一个页脚组件 . 布局和页脚组件都没有getInitialProps解决方案,那么如何以"nice"方式处理这个问题呢?

我想到的一些解决方案:

  • 我可以使用componentDidMount对页脚组件中的数据进行客户端获取(但我真的想要服务器获取/使其静态) .

  • 将页脚移动到每个页面并使 getInitialProps 可用,添加一些HOC以防止重写所有代码 .

  • 正如我所说的那样,数据是静态的,所以通过server.js或_document.js使它全局可用(虽然我不知道如何实现) .

谁可以指出我正确的方向?

1 回答

  • 1

    您可以将页眉和页脚组件放在 _app.js 中 .

    首先,在 App.getInitialProps 中,获取任何数据或执行服务器端所需的任何操作 . 然后,您返回的这些数据可以作为道具返回,并结合 Component.getInitialProps (您的页面组件的getInitialProps)的结果 .

    static async getInitialProps({ Component, ctx }) {
      let pageProps = {};
    
      // Make any initial calls we need to fetch data required for SSR
      const isAuthed = await ctx.reduxStore.dispatch(checkAuth());
    
      // Load the page getInitiaProps
      if (Component.getInitialProps) {
        pageProps = await Component.getInitialProps({ isAuthed, ...ctx });
      }
    
      return { pageProps: { ...pageProps, isAuthed } };
      // Or, if the async data is separate from your page props:
      // { pageProps, data: { isAuthed } };
    }
    

    在渲染功能中,您可以访问 this.props.pageProps (如果将其分开,则为 this.props.data ) . 然后,您可以将其传递到页眉和页脚 .

    <Header {...pageProps} />
      <main>
        <Component {...pageProps} />
      </main>
    <Footer {...pageProps} />
    

相关问题