使用 NextJS getServerSideProps 函数的 sample code:

export async function getServerSideProps(context) {
  // fetch data from an API
  const req = context.req;
  const res = context.res;
  return {
    props: {
      meetups: DUMMY_MEETUPS,
    },
  };
}

getStaticProps 只在build时生成一遍静态页面,或者定期重新生成页面不同,使用getServerSideProps,页面在每接收到一条传入请求就重新生成一遍。
因为每次请求都是从数据库读数据重新生成页面,页面加载速度会变慢。但是使用getServerSideProps 可以访问 request 对象。
如果页面不是需要每秒更新几次,或者需要访问 request 对象,那么使用getStaticProps 函数更好。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐