所以我对getStaticProps.
getStaticProps 在构建时运行以生成静态页面。
我的问题是,如果我有一个在发布新帖子时更新的博客,我不应该使用getStaticProps,对吗?因为它只在构建时被调用,然后永远不会被调用来获取新的可用帖子。在这种情况下,我应该在getServerSideProps客户端使用或获取数据useSWR,对吗?
Nic*_*ick 14
在 Next.js 中,最好将其getStaticProps视为创建静态网页的一种方式。不一定是在初始构建期间预构建的页面。
因此,如果您使用增量静态再生,则可以getStaticProps在博客文章页面上使用。
本质上,你getStaticProps用来告诉 Next.js 生成一个静态页面(或一组页面),它可能会随着时间的推移而改变。因此,您可以拥有包含所有博客文章的页面,并告诉 Next.js 它可能每天更新。
// posts.js
export const getStaticProps = async () => {
const blogPosts = await getAllBlogPosts()
return {
props: { blogPosts },
revalidate: 60 * 60 * 24 // 1 day in seconds
}
}
Run Code Online (Sandbox Code Playgroud)
这样,Next.js 将创建博客文章的静态版本,该版本会在 1 天后过期。因此,第二天,它将重新生成页面的新静态版本。这样,如果您添加新的博客文章,它将在发布之日显示。
我建议查看有关此主题的文档,因为它有更多详细信息:https : //nextjs.org/docs/basic-features/data-fetching#incremental-static-regeneration
Next.js 还可以让您添加新的博客文章页面,而无需重建整个站点。为此,您需要使用动态路由创建一个单独的博客文章页面。
首先,在posts/[slug].js. 这是一个动态路由,您可以在其中将 slug 连接到单个博客文章。
然后,添加 getStaticPaths 函数。确保将回退设置为true或blocking。文档更详细地说明了差异。
export const getStaticPaths = async () => {
return {
paths: []
fallback: 'blocking'
}
}
Run Code Online (Sandbox Code Playgroud)
这告诉 Next.js 它可以将任何东西视为 slug。这样,将来可以添加新的博客文章,而无需重建整个站点。
然后,添加您的getStaticProps函数以向页面提供详细信息。
export const getStaticProps = async (context) => {
const post = await getPostBySlug(context.params.slug)
if(!post) return { redirect: '/posts', permanent: false } // redirect to main blog posts page if post doesn't exist, or any other page you want
return {
props: { post }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3191 次 |
| 最近记录: |