Next.js 静态生成和服务器端渲染

Next.js具有两种形式的预渲染:静态生成和服务器端渲染
getStaticProps(静态生成):在构建时获取数据。
getStaticPaths(静态生成):根据数据指定要[动态]渲染的[动态路由]。
getServerSideProps(服务器端渲染):在每个请求上获取数据。

getStaticProps(静态生成)

呈现页面所需的数据可在构建时在用户请求之前获得。
该页面必须预渲染(对于SEO)并且必须非常快- getStaticProps生成HTML和JSON文件,CDN可以将它们都缓存以提高性能。

import { GetStaticProps } from 'next' // 对于TypeScript,您可以使用以下GetStaticProps类型next
export async function getStaticProps: GetStaticProps(context) {
  return {
    props: {}, // 将作为道具传递到页面组件
  }
}
getStaticPaths(静态生成)

如果页面具有动态路由并使用 getStaticProps 它,则需要定义一个在构建时必须呈现为HTML的路径列表。
如果从使用动态路由的页面导出async调用的函数getStaticPaths,则Next.js将静态预呈现由指定的所有路径getStaticPaths。
例如,假设有一个使用动态路由的页面pages/posts/[id].js。如果您getStaticPaths从此页面导出并返回以下内容paths:
getStaticPaths 仅在构建时在服务器端运行。

export async function getStaticPaths() {
  return {
    paths: [
      { params: { id: '1' } },
      { params: { id: '2' } }
    ],
    fallback: true or false 
  };
}

// 在使用 getStaticProps 静态生成
export async function getStaticProps({ params }) {
  // 参数包含post ' id '。
  // 如果路由类似/posts/1,则params。id是1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()

  // 通过道具将post数据传递到页面
  return { props: { post } }
}
getServerSideProps(服务器端渲染)

getServerSideProps仅在服务器端运行,而从不在浏览器上运行。
getServerSideProps 比 getStaticProp 花的时间要慢由于服务器必须在每个请求上计算结果,并且如果没有额外的配置,结果不能由CDN缓存。
如果不需要预渲染数据,则应考虑在客户端获取数据。

import { GetServerSideProps } from 'next' //TypeScript:使用 GetServerSideProps

export async function getServerSideProps:GetServerSideProps (context) {
  return {
    props: {}, // 将作为道具传递到页面组件
  }
}

你可能感兴趣的:(Next.js 静态生成和服务器端渲染)