Skip to main content

getInitialProps

很高兴知道:getInitialProps 是一个旧版 API。我们建议使用 getStaticPropsgetServerSideProps

¥Good to know: getInitialProps is a legacy API. We recommend using getStaticProps or getServerSideProps instead.

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

¥getInitialProps is an async function that can be added to the default exported React component for the page. It will run on both the server-side and again on the client-side during page transitions. The result of the function will be forwarded to the React component as props.

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
}

很高兴知道:

¥Good to know:

  • getInitialProps 返回的数据在服务器渲染时被序列化。确保从 getInitialProps 返回的对象是普通的 Object,而不是使用 DateMapSet

    ¥Data returned from getInitialProps is serialized when server rendering. Ensure the returned object from getInitialProps is a plain Object, and not using Date, Map or Set.

  • 对于初始页面加载,getInitialProps 将仅在服务器上运行。当使用 next/link 组件或使用 next/router 导航到不同的路由时,getInitialProps 也将在客户端上运行。

    ¥For the initial page load, getInitialProps will run on the server only. getInitialProps will then also run on the client when navigating to a different route with the next/link component or by using next/router.

  • 如果在自定义 _app.js 中使用 getInitialProps,并且导航到的页面使用 getServerSideProps,则 getInitialProps 也将在服务器上运行。

    ¥If getInitialProps is used in a custom _app.js, and the page being navigated to is using getServerSideProps, then getInitialProps will also run on the server.

上下文对象

¥Context Object

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

¥getInitialProps receives a single argument called context, which is an object with the following properties:

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

注意事项

¥Caveats

  • getInitialProps 只能在 pages/ 顶层文件中使用,不能在嵌套组件中使用。要在组件级别进行嵌套数据获取,请考虑探索 应用路由

    ¥getInitialProps can only be used in pages/ top level files, and not in nested components. To have nested data fetching at the component level, consider exploring the App Router.

  • 无论你的路由是静态还是动态,从 getInitialProps 作为 props 返回的任何数据都可以在客户端的初始 HTML 中进行检查。这是为了让页面正确为 hydrated。确保你没有传递任何不应在 props 中的客户端上可用的敏感信息。

    ¥Regardless of whether your route is static or dynamic, any data returned from getInitialProps as props will be able to be examined on the client-side in the initial HTML. This is to allow the page to be hydrated correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client in props.