# next-获取数据方式
# getInitialProps
getInitialProps在页面中启用服务器端渲染,并允许您进行初始数据填充,这意味着发送包含服务器中已填充数据的页面。这对于SEO尤其有用。
getInitialProps是一项async功能,可以作为添加到任何页面static method。看下面的例子:
function Page({ stars }) {
return <div>Next stars: {stars}</div>
}
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 Page
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
或使用类组件:
import React from 'react'
class Page extends React.Component {
static async getInitialProps(ctx) {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const json = await res.json()
return { stars: json.stargazers_count }
}
render() {
return <div>Next stars: {this.props.stars}</div>
}
}
export default Page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
对于初始页面加载,getInitialProps将仅在服务器上运行。getInitialProps通过next/link组件或使用导航到其他路由时,它将在客户端上运行。
# 上下文对象
getInitialProps收到一个称为的参数context,它是一个具有以下属性的对象:
- pathname-当前路线。那是页面的路径/pages
- query -将URL的查询字符串部分解析为对象
- asPath-String浏览器中显示的实际路径(包括查询)
- req- HTTP请求对象(服务器只)
- res- HTTP响应对象(服务器只)
- err -渲染期间遇到任何错误的错误对象
# 注意事项
- getInitialProps能不能在子组件中使用,只能在每个页面的默认出口
- 如果您在内部使用仅服务器端的模块getInitialProps,请确保正确导入它们,否则会降低应用程序的速度
← next-动态路由 next-自定义App →