跳到内容
API 参考函数getInitialProps

getInitialProps

须知getInitialProps 是一个旧版 API。我们建议改用 getStaticPropsgetServerSideProps

getInitialProps 是一个 async 函数,可以添加到页面的默认导出 React 组件中。它将在页面转换期间在服务器端和客户端上再次运行。该函数的结果将作为 props 转发到 React 组件。

pages/index.tsx
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 返回的数据在服务器渲染时会被序列化。请确保从 getInitialProps 返回的对象是一个纯 Object,并且不使用 DateMapSet
  • 对于初始页面加载,getInitialProps 将仅在服务器上运行。当使用 next/link 组件或 next/router 导航到不同的路由时,getInitialProps 也将在客户端上运行。
  • 如果 getInitialProps 在自定义 _app.js 中使用,并且导航到的页面正在使用 getServerSideProps,那么 getInitialProps 也将在服务器上运行。

上下文对象

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

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

注意事项

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