next.js - 当覆盖 _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>
}
}
解决方案
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 产生的初始道具实例化组件。
推荐阅读
- python - 在 Windows 中安装 Pip Cryptography 的问题
- javascript - 如何根据电子邮件模式的输入状态禁用按钮?
- xamarin - 如何使框架内容尊重其角半径?
- python - 我可以将下载的压缩 shapefile 解压缩到内存中以上传到数据库吗?
- javascript - 存储在对象中时如何从模板文字中删除空格?
- react-native - React-Native:Azure Pipelines 中的任务失败,但在本地却没有
- java - 如何在 Exo Player 中使用查询参数?
- c# - Razor Pages 链接基于当前页面错误呈现
- angular - 为什么我的 SafeResourceUrl 在同一类的方法中未定义
- javascript - JS:如何删除“垃圾邮件隐形字符”?