首页 > 解决方案 > 当覆盖 _app.js 时 getInitialProps 用于什么?

问题描述

这到底是做什么的?

pageProps = 等待 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>
  }
}

标签: next.js

解决方案


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 产生的初始道具实例化组件。


推荐阅读