服务端渲染 (SSR)
也称为 “SSR” 或 “动态渲染”。
如果页面使用服务端渲染,则页面 HTML 会在每次请求时生成。
要为一个页面使用服务端渲染,你需要 export
一个名为 getServerSideProps
的 async
函数。此函数将在每次请求时由服务器调用。
例如,假设你的页面需要预渲染频繁更新的数据(从外部 API 获取)。你可以编写 getServerSideProps
,它会获取此数据并将其传递给 Page
,如下所示
export default function Page({ data }) {
// Render data...
}
// This gets called on every request
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
正如你所看到的,getServerSideProps
类似于 getStaticProps
,但不同之处在于 getServerSideProps
在每次请求时运行,而不是在构建时运行。
要了解更多关于 getServerSideProps
如何工作的信息,请查看我们的数据获取文档。
这是否有帮助?