我目前正在使用 NextJS 13.5 构建电子商务。
在 app/products/[slug]/page.jsx 我有产品名称、描述、价格和其他产品相关信息。我使用
generateStaticParams()
函数以便使用 next build
静态构建每个产品页面。
话虽如此,我面临的问题是产品的价格不能是静态的! 产品价格经常变化,有时甚至每天变化。
即使产品页面的其余部分(名称、描述等)是静态的,并且基本上是 SSG,我如何才能使每个产品的价格都是动态的并在每次访问时从数据库中获取?
任何知识或想法表示赞赏! 🤗🙏
读你的问题时我有两个想法。第一个应该可以在 Next.js 13 上访问,第二个需要更新到 14。
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>
)
}
如果您升级到 14,您可以选择使用此实验性功能。
当用户访问路线时:
- 提供静态路由 shell,这使得初始加载速度更快。
- shell 留下了一些漏洞,动态内容将在其中异步加载。
- 异步孔并行加载,减少页面的整体加载时间。
这与您现在的应用程序的行为不同,整个路由要么是完全静态的,要么是动态的。
API参考:https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering
教程:https://nextjs.org/learn/dashboard-app/partial-prerendering