getInitialProps

须知getInitialProps 是一个遗留 API。我们推荐使用 getStaticPropsgetServerSideProps 替代。

getInitialProps 是一个 async 函数,可以添加到页面默认导出的 React 组件中。它会在服务端运行,并在页面切换时在客户端再次运行。该函数的返回结果会作为 props 传递给 React 组件。

import { NextPageContext } from 'next'

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

export default function Page({ stars }: { stars: number }) {
  return stars
}

须知

  • getInitialProps 返回的数据在服务端渲染时会被序列化。确保返回的对象是一个普通的 Object,而不是 DateMapSet
  • 对于初始页面加载,getInitialProps 仅在服务端运行。当通过 next/link 组件或 next/router 导航到其他路由时,getInitialProps 也会在客户端运行。
  • 如果在自定义的 _app.js 中使用了 getInitialProps,并且导航到的页面使用了 getServerSideProps,那么 getInitialProps 也会在服务端运行。

Context 对象

getInitialProps 接收一个名为 context 的参数,它是一个包含以下属性的对象:

名称描述
pathname当前路由,即 /pages 中页面的路径
queryURL 的查询字符串,解析为对象
asPath浏览器中显示的实际路径(包括查询参数)的字符串
reqHTTP 请求对象(仅服务端)
resHTTP 响应对象(仅服务端)
err渲染过程中遇到的错误对象

注意事项

  • getInitialProps 只能在 pages/ 顶级文件中使用,不能在嵌套组件中使用。如需在组件级别进行嵌套数据获取,请考虑使用 App Router
  • 无论你的路由是静态还是动态,任何从 getInitialProps 返回并作为 props 的数据都可以在客户端的初始 HTML 中被查看。这是为了确保页面能够正确注水 (hydrate)。请确保不要在 props 中传递任何不应在客户端暴露的敏感信息。

On this page