Next.js 9.3引入以下三个API:
- getStaticProps
- getStaticPaths
- getServerSideProps
前提知识
SSG
Next.js根据pages目录中的文件名进行路由设定
getInitialProps
getInitialProps是在渲染页面之前就会运行的API。 如果该路径下包含该请求,则执行该请求,并将所需的数据作为props传递给页面。 (实际上有时会有发送日志等不影响HTML的副作用。 ) 与此次介绍的3个API一样,只能在pages文件夹内的文件中使用。 getInitialProps是SSR专用的API,这是误解。 直接访问后,getInitialProps将在服务器端运行。 另一方面,使用next/link进行客户端路由时,在客户端执行。 因此,建议使用isomorphic-unfetch等fetch库。
//pages/stars.js
// 用于客户端和服务器端
import fetch from 'isomorphic-unfetch'
// getInitialProps中获取返回的数据stars
function Stars({ stars }) {
return <div>Next stars: {stars}</div>
}
// 先执行获取数据
Stars.getInitialProps = async () => {
const res = await fetch('https://api.github.com/repos/zeit/next.js')
const json = await res.json()
return { stars: json.stargazers_count }
}
export default Stars
getStaticProps
getStaticProps是用于在构建时预先执行getInitialProps进行的处理并预先生成静态文件的API。 不会在客户端上运行。 始终在服务器端运行。
//pages/buildTimeStars.js
// 不在客户端运行
import fetch from 'node-fetch'
// getStaticProps中返回的stars, build_time数据
function BuildTimeStars({ stars, build_time }) {
return <div>ビルド時({build_time})のNextのstar数は: {stars}</div>
}
// 在构建时运行
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/zeit/next.js')
const json = await res.json()
const stars = json.stargazers_count
const build_time = new Date().toString();
return {
props: {
stars,
build_time
},
}
}
export default BuildTimeStars
Dynamic Routes
在pages文件夹中的文件名中添加一个括号[]以启用动态路由。(pages/posts/[pid].js)
//pages/posts/[pid].js
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { pid } = router.query
return <p>Post: {pid}</p>
}
export default Post
//posts/abc
<div id="__next">
<p>Post: abc</p>
</div>
//posts/hoge
<div id="__next">
<p>Post: hoge</p>
</div>
getStaticPaths
用于在使用动态路由时生成静态文件。
//zeit/[name].js
import fetch from 'node-fetch'
function Zeit({ name, stars }) {
return <div>{name} stars: {stars}</div>
}
// 首先执行。 返回路径以使用数组进行预构建。
export async function getStaticPaths() {
// zeit获取30个由API管理的存储库
const res = await fetch('https://api.github.com/orgs/zeit/repos')
const repos = await res.json()
// 存储库名称的路径
const paths = repos.map(repo => `/zeit/${repo.name}`)
return { paths, fallback: false }
}
// 接收带有路由信息的参数
export async function getStaticProps({ params }) {
// 对应于文件名zeit/[name].js
const name = params.name
const res = await fetch(`https://api.github.com/repos/zeit/${name}`)
const json = await res.json()
const stars = json.stargazers_count
return { props: { name, stars } }
}
export default Zeit
// /zeit/ms
<div id="__next">
<div>ms stars: 2699</div>
</div>
// /zeit/micro
<div id="__next">
<div>micro stars: 9128</div>
</div>
getStaticProps的必需参数为paths和fallback。 它决定访问预构建路径以外的路径时的行为。
- false
其他路由为404 - true
如果fallback设置为true,则即使未预构建的路径也不会为404
结论
服务端 | 客户端 | 执行时间 | |
---|---|---|---|
getStaticProps | true | false | 在构建时(根据要求,如果+ fallback = true) |
getStaticPaths | true | false | 仅在建造时 |
getServerSideProps | true | false | 根据要求 |
getInitialProps | true | true | 根据要求 |