Next.js:我可以对内部有动态组件的页面使用generateStaticParams吗?即有一个特定的组件每次都获取数据并渲染

问题描述 投票:0回答:1

我目前正在使用 NextJS 13.5 构建电子商务。

app/products/[slug]/page.jsx 我有产品名称、描述、价格和其他产品相关信息。我使用

generateStaticParams()
函数以便使用
next build
静态构建每个产品页面。

话虽如此,我面临的问题是产品的价格不能是静态的! 产品价格经常变化,有时甚至每天变化。

即使产品页面的其余部分(名称、描述等)是静态的,并且基本上是 SSG,我如何才能使每个产品的价格都是动态的并在每次访问时从数据库中获取?

任何知识或想法表示赞赏! 🤗🙏

next.js e-commerce server-side-rendering static-site-generation generatestaticparams
1个回答
0
投票

读你的问题时我有两个想法。第一个应该可以在 Next.js 13 上访问,第二个需要更新到 14。

1.将
fetch
cache: 'no-store'

一起使用

我在 Next.js 页面 -> App Router 迁移指南中找到了一些信息,我相信这些信息与您的情况相关。

说明:

通过将

cache
选项设置为
no-store
,我们可以指示永远不应缓存所获取的数据。这类似于页面目录中的
getServerSideProps

示例:

// `app` directory
 
// This function can be named anything
async function getProjects() {
  const res = await fetch(`https://...`, { cache: 'no-store' })
  const projects = await res.json()
 
  return projects
}
 
export default async function Dashboard() {
  const projects = await getProjects()
 
  return (
    <ul>
      {projects.map((project) => (
        <li key={project.id}>{project.name}</li>
      ))}
    </ul>
  )
}

链接

来源:https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#server-side-rendering-getserversideprops

2.部分预渲染

如果您升级到 14,您可以选择使用此实验性功能。

说明:

当用户访问路线时:

  • 提供静态路由 shell,这使得初始加载速度更快。
  • shell 留下了一些漏洞,动态内容将在其中异步加载。
  • 异步孔并行加载,减少页面的整体加载时间。

这与您现在的应用程序的行为不同,整个路由要么是完全静态的,要么是动态的。

链接

API参考:https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering

教程:https://nextjs.org/learn/dashboard-app/partial-prerendering

© www.soinside.com 2019 - 2024. All rights reserved.