当使用 NextJS 构建静态站点时,我希望 getInitialProps
方法仅在构建步骤期间触发,而不是在客户端触发。
在构建步骤中,NextJS 运行 getInitialProps method在每个组件的渲染 HTML 用于生成页面的静态 HTML 之前。在客户端,NextJS 也会在页面组件渲染之前运行此方法,以便为该组件返回必要的 props。因此,大请求可能会延迟客户端的第一次绘制,因为这是一个阻塞请求。
// 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,而这个特定的构建后请求不需要是动态的或更新的。
有没有办法让getInitialProps
只在next export
构建时运行,不作为客户端加载页面?
这是好的做法吗?
最佳答案
我找到了 NextJs 9.0.3 的解决方法(其他版本也可能有效,我没有测试)
// XXXPage is your page
XXXPage.getInitialProps = async (req) => {
if (process.browser) {
return __NEXT_DATA__.props.pageProps;
}
// original logic
}
关于javascript - 如何仅在 NextJS 站点构建期间使用 getInitialProps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57897785/