如何仅在 NextJS 站点构建期间使用 getInitialProps? [英] How can I use getInitialProps only during the NextJS site build?

查看:29
本文介绍了如何仅在 NextJS 站点构建期间使用 getInitialProps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 NextJS 构建静态站点时,我希望 getInitialProps 方法仅在构建步骤期间触发,而不是在客户端上触发.

When using NextJS to build a static site, I would like the getInitialProps method to fire only during the build step and not on the client.

在构建步骤中,NextJS 在每个之前运行 getInitialProps 方法组件的渲染 HTML 用于生成页面的静态 HTML.在客户端,NextJS 也会在页面组件渲染之前运行此方法,以便为组件返回必要的 props.因此,大型请求可能会延迟客户端的第一次绘制,因为这是一个阻塞请求.

In the build step, NextJS runs the getInitialProps method before each component's rendered HTML is used to generate the page's static HTML. On the client, NextJS also runs this method before the page component is rendered in order to return the necessary props for the component. Thus, large requests can delay the client's first paint as this is a blocking request.

// example usage of API call in getInitialProps
import fetch from 'isomorphic-unfetch'

function Page({ stars }) {
  return <div>Next stars: {stars}</div>
}

Page.getInitialProps = async ({ req }) => {
  const res = await fetch('https://api.github.com/repos/zeit/next.js')
  const json = await res.json()
  return { stars: json.stargazers_count }
}

export default Page

我不愿意将我的慢速 API 请求移动到 componentDidMount 以避免阻塞请求,因为我想使用在构建步骤中返回的数据来填充静态 HTML,并且这个特殊的构建后请求不需要是动态的或更新的.

I'm unwilling to move my slow API request to componentDidMount in order to avoid the blocking request because I want to use the data returned during the build step to populate the static HTML, and this particular request doesn't need to be dynamic or updated after the build.

有没有办法让 getInitialPropsnext export 构建时运行 onlynot 作为客户端加载页面?

Is there a way I can make getInitialProps run only when next export builds and not as the client loads the page?

这是好的做法吗?

推荐答案

我找到了 NextJs 9.0.3 的解决方法(其他版本也可以,我没有测试)

I found the workaround with NextJs 9.0.3 (other versions may also work, I didn't test that)

// XXXPage is your page

XXXPage.getInitialProps = async (req) => {
  if (process.browser) {
    return __NEXT_DATA__.props.pageProps;
  }
  // original logic
}

这篇关于如何仅在 NextJS 站点构建期间使用 getInitialProps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆