Skip to main content

服务器端渲染 (SSR)

也称为 "SSR" 或 "动态渲染"。

¥Also referred to as "SSR" or "Dynamic Rendering".

如果页面使用服务器端渲染,则每个请求都会生成页面 HTML。

¥If a page uses Server-side Rendering, the page HTML is generated on each request.

要对页面使用服务器端渲染,你需要 export 一个名为 getServerSidePropsasync 函数。服务器将在每次请求时调用此函数。

¥To use Server-side Rendering for a page, you need to export an async function called getServerSideProps. This function will be called by the server on every request.

例如,假设你的页面需要预渲染经常更新的数据(从外部 API 获取)。你可以编写 getServerSideProps 来获取此数据并将其传递给 Page,如下所示:

¥For example, suppose that your page needs to pre-render frequently updated data (fetched from an external API). You can write getServerSideProps which fetches this data and passes it to Page like below:

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 } }
}

正如你所看到的,getServerSidePropsgetStaticProps 类似,但不同之处在于 getServerSideProps 在每个请求上运行,而不是在构建时运行。

¥As you can see, getServerSideProps is similar to getStaticProps, but the difference is that getServerSideProps is run on every request instead of on build time.

要了解有关 getServerSideProps 如何工作的更多信息,请查看我们的 数据获取文档

¥To learn more about how getServerSideProps works, check out our Data Fetching documentation.