getServerSideProps
当从页面中导出一个名为 `getServerSideProps`(服务器端渲染)的函数时,Next.js 将使用 `getServerSideProps` 返回的数据在每个请求上预渲染此页面。这在您想要获取经常变化的数据,并希望页面更新以显示最新数据时很有用。
pages/index.tsx
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getServerSideProps = (async () => {
// Fetch data from external API
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo: Repo = await res.json()
// Pass data to the page via props
return { props: { repo } }
}) satisfies GetServerSideProps<{ repo: Repo }>
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<main>
<p>{repo.stargazers_count}</p>
</main>
)
}您可以在顶层作用域中导入模块以在 `getServerSideProps` 中使用。使用的导入将**不会为客户端打包**。这意味着您可以**直接在 `getServerSideProps` 中编写服务器端代码**,包括从数据库中获取数据。
上下文参数
context 参数是一个包含以下键的对象
| 名称 | 描述 |
|---|---|
params | 如果此页面使用动态路由,则 `params` 包含路由参数。如果页面名称为 `[id].js`,则 `params` 将类似于 `{ id: ... }`。 |
请求(req) | `HTTP` IncomingMessage 对象,带有一个额外的 `cookies` 属性,它是一个将字符串键映射到 cookie 字符串值的对象。 |
响应(res) | HTTP 响应对象. |
查询(query) | 一个表示查询字符串的对象,包括动态路由参数。 |
preview | (已弃用,请使用 `draftMode`)如果页面处于预览模式,`preview` 为 `true`,否则为 `false`。 |
预览数据(previewData) | (已弃用,请使用 `draftMode`)由 `setPreviewData` 设置的预览数据。 |
draftMode | 如果页面处于草稿模式,`draftMode` 为 `true`,否则为 `false`。 |
解析后的 URL(resolvedUrl) | 请求 `URL` 的规范化版本,它会剥离客户端转换的 `_next/data` 前缀并包含原始查询值。 |
locale | 包含活动的语言环境(如果已启用)。 |
locales | 包含所有受支持的语言环境(如果已启用)。 |
defaultLocale | 包含已配置的默认语言环境(如果已启用)。 |
getServerSideProps 返回值
`getServerSideProps` 函数应返回一个包含**以下任一**属性的对象
`props`
`props` 对象是键值对,每个值都由页面组件接收。它应该是一个可序列化对象,以便任何传递的 props 都可以通过`JSON.stringify` 进行序列化。
export async function getServerSideProps(context) {
return {
props: { message: `Next.js is awesome` }, // will be passed to the page component as props
}
}`notFound`
`notFound` 布尔值允许页面返回 `404` 状态和404 页面。即使之前成功生成了页面,设置 `notFound: true` 也会使页面返回 `404`。这旨在支持用户生成内容被作者删除等用例。
export async function getServerSideProps(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
}
}`redirect`
`redirect` 对象允许重定向到内部和外部资源。它应该符合 `{ destination: string, permanent: boolean }` 的形式。在某些罕见情况下,您可能需要为较旧的 `HTTP` 客户端分配自定义状态码才能正确重定向。在这些情况下,您可以使用 `statusCode` 属性而不是 `permanent` 属性,但不能同时使用。
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {}, // will be passed to the page component as props
}
}版本历史
| 版本 | 更改 |
|---|---|
v13.4.0 | App Router 现已稳定,并简化了数据获取 |
v10.0.0 | 添加了 `locale`、`locales`、`defaultLocale` 和 `notFound` 选项。 |
v9.3.0 | 引入了 `getServerSideProps`。 |
这有帮助吗?