getInitialProps
提示:
getInitialProps是一个旧版 API。我们建议改用getStaticProps或getServerSideProps。
getInitialProps 是一个可以添加到页面默认导出的 React 组件的 async 函数。它将在服务端运行,并在页面转换期间再次在客户端运行。函数的结果将作为 props 转发到 React 组件。
- TypeScript
- JavaScript
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
}
pages/index.js
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返回的数据在服务端渲染时会被序列化。确保从getInitialProps返回的对象是纯Object,而不是使用Date、Map或Set。- 对于初始页面加载,
getInitialProps仅在服务器上运行。然后,当使用next/link组件或使用next/router导航到不同的路由时,getInitialProps也会在客户端运行。- 如果在自定义
_app.js中使用getInitialProps,并且导航到的页面正在使用getServerSideProps,则getInitialProps也将在服务器上运行。
Context 对象
getInitialProps 接收一个名为 context 的参数,它是一个具有以下属性的对象:
| 名称 | 描述 |
|---|---|
pathname | 当前路由,/pages 中页面的路径 |
query | URL 的查询字符串,解析为对象 |
asPath | 浏览器中显示的实际路径的 String(包括查询) |
req | HTTP 请求对象(仅服务端) |
res | HTTP 响应对象(仅服务端) |
err | 如果在渲染期间遇到任何错误,则为错误对象 |