getInitialProps
须知:
getInitialProps是一个遗留 API。我们推荐使用getStaticProps或getServerSideProps替代。
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
}Page.getInitialProps = async (ctx) => {
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 }) {
return stars
}须知:
- 从
getInitialProps返回的数据在服务端渲染时会被序列化。请确保返回的对象是一个普通Object,不要使用Date、Map或Set。- 对于初始页面加载,
getInitialProps仅会在服务端运行。当通过next/link组件或next/router导航到其他路由时,getInitialProps也会在客户端运行。- 如果在自定义
_app.js中使用了getInitialProps,并且导航到的页面使用了getServerSideProps,那么getInitialProps也会在服务端运行。
上下文对象
getInitialProps 接收一个名为 context 的参数,它是一个包含以下属性的对象:
| 名称 | 描述 |
|---|---|
pathname | 当前路由,即 /pages 中页面的路径 |
query | URL 的查询字符串,解析为对象 |
asPath | 浏览器中显示的实际路径(包含查询参数)的字符串 |
req | HTTP 请求对象(仅服务端) |
res | HTTP 响应对象(仅服务端) |
err | 渲染过程中遇到的错误对象 |
注意事项
getInitialProps只能在pages/顶级文件中使用,不能在嵌套组件中使用。如需在组件级别实现嵌套数据获取,请考虑使用 App Router。- 无论你的路由是静态还是动态,从
getInitialProps返回的任何作为props的数据都可以在初始 HTML 的客户端被检查。这是为了确保页面能够正确水合 (hydrate)。请确保不要在props中传递任何不应在客户端可用的敏感信息。