跳到主要内容

getInitialProps

提示getInitialProps 是一个旧版 API。我们建议改用 getStaticPropsgetServerSideProps

getInitialProps 是一个可以添加到页面默认导出的 React 组件的 async 函数。它将在服务端运行,并在页面转换期间再次在客户端运行。函数的结果将作为 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 也会在客户端运行。
  • 如果在自定义 _app.js 中使用 getInitialProps,并且导航到的页面正在使用 getServerSideProps,则 getInitialProps 也将在服务器上运行。

Context 对象

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

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

注意事项

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