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

查看:271
本文介绍了仅在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还在呈现页面组件之前运行此方法,以便为该组件返回必要的道具.因此,大请求可能会延迟客户端的第一次绘画,因为这是一个阻塞请求.

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.

有没有一种方法可以使getInitialProps仅在构建next export时运行 而在客户端加载页面时运行?

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天全站免登陆