getStaticProps
导出名为 getStaticProps
的函数将在构建时使用从该函数返回的 props 预渲染页面:
¥Exporting a function called getStaticProps
will pre-render a page at build time using the props returned from the function:
import type { InferGetStaticPropsType, GetStaticProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getStaticProps = (async (context) => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}) satisfies GetStaticProps<{
repo: Repo
}>
export default function Page({
repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return repo.stargazers_count
}
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}
export default function Page({ repo }) {
return repo.stargazers_count
}
你可以导入顶层范围内的模块以在 getStaticProps
中使用。使用的导入不会为客户端打包。这意味着你可以直接在 getStaticProps
中编写服务器端代码,包括从数据库中获取数据。
¥You can import modules in top-level scope for use in getStaticProps
. Imports used will not be bundled for the client-side. This means you can write server-side code directly in getStaticProps
, including fetching data from your database.
上下文参数
¥Context parameter
context
参数是一个包含以下键的对象:
¥The context
parameter is an object containing the following keys:
名称 | 描述 |
---|---|
params | 包含使用 动态路由 的页面的路由参数。例如,如果页面名称是 [id].js ,那么 params 将看起来像 { id: ... } 。你应该将其与 getStaticPaths 一起使用,我们稍后将对此进行解释。 |
preview | (draftMode 已弃用)如果页面位于 预览模式 中,则 preview 为 true ,否则为 false 。 |
previewData | (draftMode 已弃用)preview 数据由 setPreviewData 设置。 |
draftMode | 如果页面位于 草稿模式 中,则 draftMode 为 true ,否则为 false 。 |
locale | 包含活动区域设置(如果启用)。 |
locales | 包含所有支持的区域设置(如果启用)。 |
defaultLocale | 包含配置的默认区域设置(如果启用)。 |
revalidateReason | 提供调用该函数的原因。可以是以下之一:"build"(在构建时运行)、"stale"(重新验证期已过,或在 开发模式 中运行)、"on-demand"(通过 按需重新验证 触发) |
getStaticProps 返回值
¥getStaticProps return values
getStaticProps
函数应返回一个包含 props
、redirect
或 notFound
的对象,后跟可选的 revalidate
属性。
¥The getStaticProps
function should return an object containing either props
, redirect
, or notFound
followed by an optional revalidate
property.
props
props
对象是一个键值对,其中每个值都由页面组件接收。它应该是 可序列化对象,这样任何传递的 props 都可以用 JSON.stringify
序列化。
¥The props
object is a key-value pair, where each value is received by the page component. It should be a serializable object so that any props passed, could be serialized with JSON.stringify
.
export async function getStaticProps(context) {
return {
props: { message: `Next.js is awesome` }, // will be passed to the page component as props
}
}
revalidate
revalidate
属性是页面重新生成之前的秒数(默认为 false
或不重新验证)。
¥The revalidate
property is the amount in seconds after which a page re-generation can occur (defaults to false
or no revalidation).
// This function gets called at build time on server-side.
// It may be called again, on a serverless function, if
// revalidation is enabled and a new request comes in
export async function getStaticProps() {
const res = await fetch('https://.../posts')
const posts = await res.json()
return {
props: {
posts,
},
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 10 seconds
revalidate: 10, // In seconds
}
}
了解有关 增量静态再生 的更多信息。
¥Learn more about Incremental Static Regeneration.
利用 ISR 的页面的缓存状态可以通过读取 x-nextjs-cache
响应标头的值来确定。可能的值如下:
¥The cache status of a page leveraging ISR can be determined by reading the value of the x-nextjs-cache
response header. The possible values are the following:
-
MISS
- 该路径不在缓存中(最多出现一次,在第一次访问时)¥
MISS
- the path is not in the cache (occurs at most once, on the first visit) -
STALE
- 该路径在缓存中,但超出了重新验证时间,因此它将在后台更新¥
STALE
- the path is in the cache but exceeded the revalidate time so it will be updated in the background -
HIT
- 该路径在缓存中并且未超过重新验证时间¥
HIT
- the path is in the cache and has not exceeded the revalidate time
notFound
notFound
布尔值允许页面返回 404
状态和 404 页面。对于 notFound: true
,即使之前已经成功生成过页面,页面也会返回 404
。这是为了支持用户生成的内容被作者删除等用例。请注意,notFound
遵循与 此处描述 相同的 revalidate
行为。
¥The notFound
boolean allows the page to return a 404
status and 404 Page. With notFound: true
, the page will return a 404
even if there was a successfully generated page before. This is meant to support use cases like user-generated content getting removed by its author. Note, notFound
follows the same revalidate
behavior described here.
export async function getStaticProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
return {
props: { data }, // will be passed to the page component as props
}
}
很高兴知道:
fallback: false
模式不需要notFound
,因为只有从getStaticPaths
返回的路径才会被预渲染。¥Good to know:
notFound
is not needed forfallback: false
mode as only paths returned fromgetStaticPaths
will be pre-rendered.
redirect
redirect
对象允许重定向到内部或外部资源。它应该与 { destination: string, permanent: boolean }
的形状相匹配。
¥The redirect
object allows redirecting to internal or external resources. It should match the shape of { destination: string, permanent: boolean }
.
在极少数情况下,你可能需要为较旧的 HTTP
客户端分配自定义状态代码才能正确重定向。在这些情况下,你可以使用 statusCode
属性而不是 permanent
属性,但不能同时使用两者。你还可以设置 basePath: false
,类似于 next.config.js
中的重定向。
¥In some rare cases, you might need to assign a custom status code for older HTTP
clients to properly redirect. In these cases, you can use the statusCode
property instead of the permanent
property, but not both. You can also set basePath: false
similar to redirects in next.config.js
.
export async function getStaticProps(context) {
const res = await fetch(`https://...`)
const data = await res.json()
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
// statusCode: 301
},
}
}
return {
props: { data }, // will be passed to the page component as props
}
}
如果重定向在构建时已知,则应将其添加到 next.config.js
中。
¥If the redirects are known at build-time, they should be added in next.config.js
instead.
读取文件:使用 process.cwd()
¥Reading files: Use process.cwd()
可以直接从 getStaticProps
中的文件系统读取文件。
¥Files can be read directly from the filesystem in getStaticProps
.
为此,你必须获取文件的完整路径。
¥In order to do so you have to get the full path to a file.
由于 Next.js 将代码编译到单独的目录中,因此你不能使用 __dirname
,因为它返回的路径与页面路由不同。
¥Since Next.js compiles your code into a separate directory you can't use __dirname
as the path it returns will be different from the Pages Router.
相反,你可以使用 process.cwd()
,它为你提供执行 Next.js 的目录。
¥Instead you can use process.cwd()
which gives you the directory where Next.js is being executed.
import { promises as fs } from 'fs'
import path from 'path'
// posts will be populated at build time by getStaticProps()
function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>
<h3>{post.filename}</h3>
<p>{post.content}</p>
</li>
))}
</ul>
)
}
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
const postsDirectory = path.join(process.cwd(), 'posts')
const filenames = await fs.readdir(postsDirectory)
const posts = filenames.map(async (filename) => {
const filePath = path.join(postsDirectory, filename)
const fileContents = await fs.readFile(filePath, 'utf8')
// Generally you would parse/transform the contents
// For example you can transform markdown to HTML here
return {
filename,
content: fileContents,
}
})
// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
posts: await Promise.all(posts),
},
}
}
export default Blog
版本历史
¥Version History
版本 | 变化 |
---|---|
v13.4.0 | 应用路由 现已稳定并简化了数据获取 |
v12.2.0 | 按需增量静态再生 稳定。 |
v12.1.0 | 添加了 按需增量静态再生(测试版)。 |
v10.0.0 | 添加了 locale 、locales 、defaultLocale 和 notFound 选项。 |
v10.0.0 | 添加了 fallback: 'blocking' 返回选项。 |
v9.5.0 | 稳定 增量静态再生 |
v9.3.0 | getStaticProps 推出。 |