【问题标题】:next.js getInitialProps in a global layout component全局布局组件中的 next.js getInitialProps
【发布时间】:2018-08-24 11:41:16
【问题描述】:

我正在使用 next.js 构建一个网站,我正试图解决以下“问题”。我有一些需要从 API 端点(无头 CMS)获取的静态数据(网站文本)。

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

我想到的一些解决方案:

  1. 我可以使用 componentDidMount 对页脚组件中的数据进行客户端提取(但我真的希望服务器提取/使其成为静态)。
  2. 将页脚移动到每一页并提供getInitialProps,添加一些 HOC 以防止重写所有代码。
  3. 正如我所说,数据是静态的,因此通过 server.js 或 _document.js 使其在全球范围内可用(不过我不知道如何实现)。

谁能指出我正确的方向?

【问题讨论】:

    标签: javascript next.js


    【解决方案1】:

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

    首先,在App.getInitialProps 中,获取任何数据或执行您需要在服务器端发生的任何操作。然后,您返回的这些数据可以作为 props 返回,并结合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} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-09
      • 2022-01-10
      • 1970-01-01
      • 2021-05-16
      • 2020-05-31
      • 2019-10-12
      • 2020-10-14
      相关资源
      最近更新 更多