【问题标题】:At what stage getStaticProps() fetch the data from my API?在什么阶段 getStaticProps() 从我的 API 获取数据?
【发布时间】:2022-02-15 02:46:23
【问题描述】:

我试图了解 getStaticProps 究竟何时获取数据。

是在构建过程中还是在每次将网站呈现给某人时(每次有人访问我的应用程序时)

如果它是第一个,它不会使我的应用程序“静态”,这意味着当我的数据库中的数据发生更改时它不会更新数据?

谢谢!!

【问题讨论】:

标签: next.js


【解决方案1】:

我要睡觉了所以我刚刚从NextJS Docs复制了下面的答案

Next.js 允许您在构建网站后创建或更新静态页面。增量静态重新生成 (ISR) 使您能够在每页的基础上使用静态生成,而无需重建整个站点。借助 ISR,您可以在扩展到数百万页的同时保留静态的优势。

要使用 ISR,请将 revalidate 属性添加到 getStaticProps:

function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}
export async function getStaticProps() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  return {
    props: {
      posts,
    },
    // Next.js will attempt to re-generate the page:
    // - When a request comes in
    // - At most once every 10 seconds
    revalidate: 10, // In seconds
  }
}
export async function getStaticPaths() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.id },
  }))

  // We'll pre-render only these paths at build time.
  // { fallback: blocking } will server-render pages
  // on-demand if the path doesn't exist.
  return { paths, fallback: 'blocking' }
}

【讨论】:

  • 谢谢!我会看一下。但是 ISR 听起来很酷 =)
猜你喜欢
  • 2021-06-11
  • 2021-01-17
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多