当覆盖 _app.js 时,getInitialProps 用于什么?

cra*_*ngs 7 next.js

这到底是做什么的?

pageProps = await Component.getInitialProps(ctx)

看起来“pageProps”这只是一个空对象

import App, {Container} from 'next/app'
import React from 'react'

export default class MyApp extends App {
  static async getInitialProps ({ Component, router, ctx }) {
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return {pageProps}
  }

  render () {
    const {Component, pageProps} = this.props
    return <Container>
      <Component {...pageProps} />
    </Container>
  }
}
Run Code Online (Sandbox Code Playgroud)

ste*_*tef 8

getInitialProps 允许您调用以获取您希望组件在服务器上呈现时具有的道具。

例如,我可能需要显示当前天气,并且我希望 Google 使用该信息为我的页面编制索引以用于 SEO 目的。

为了实现这一点,你会做这样的事情:

import React from 'react' import 'isomorphic-fetch' const HomePage = (props) => ( <div> Weather today is: {weather} </div> ) HomePage.getInitialProps = async ({ req }) => { const res = await fetch('https://my.weather.api/london/today') const json = await res.json() return { weather: json.today } } export default HomePage

该行pageProps = await Component.getInitialProps(ctx)调用该初始函数,以便HomePage使用对该天气 API 调用产生的初始道具实例化该组件。

  • 在页面内使用的 getInitialProps 和在 _app.js 中运行的 getInitialProps 之间存在差异,更多信息在这里; https://spectrum.chat/next-js/general/getinitialprops-confusion-in-the-docs-about-parameters~07e9ab0e-0fae-43a8-8bc0-350c79e921a3 (8认同)