You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13使用Link组件切换路由时如何获取最新数据?

解决方案:Link路由切换时获取最新数据的问题

你遇到的核心问题是Next.js默认会缓存Server Component中的fetch请求结果,即使加了dynamic='force-dynamic',缓存的请求数据还是会被复用,导致Link切换路由时无法拿到最新的帖子数据。

1. 修复数据请求的缓存问题

找到@/requests/posts里的getPosts函数,给内部的fetch请求添加cache: 'no-store'选项,强制每次请求都从数据库拉取最新数据:

// @/requests/posts.js
export async function getPosts() {
  const res = await fetch('/api/你的帖子接口地址', {
    cache: 'no-store', // 禁用请求缓存
  });
  if (!res.ok) throw new Error('Failed to fetch posts');
  return res.json();
}

也可以用next: { revalidate: 0 }达到同样效果:

const res = await fetch('/api/你的帖子接口地址', {
  next: { revalidate: 0 }, // 立即失效缓存
});

2. 确保页面动态渲染配置生效

你已经添加的export const dynamic = 'force-dynamic';是正确的,它会让页面每次请求都在服务器重新渲染。如果仍有问题,可以替换成export const revalidate = 0;,两者功能等价,都是强制动态渲染。

3. 修复代码中的小bug

页面组件里渲染PostCard时用了async,这会导致React渲染Promise对象而非组件,直接去掉async即可:

// 错误写法
posts?.reverse().map(async (post) => {
  return <PostCard key={post._id} ... />
})

// 正确写法
posts?.reverse().map((post) => {
  return <PostCard key={post._id} ... />
})

为什么这样能解决问题?

  • Next.js的fetch默认会缓存请求结果,哪怕页面是动态的,缓存数据也会被复用,必须显式禁用缓存才能拿到最新数据。
  • dynamic='force-dynamic'或revalidate=0确保页面每次路由切换(包括Link跳转)都会触发服务器重新渲染,结合禁用缓存的fetch请求,就能保证每次都获取最新的帖子数据。

内容的提问来源于stack exchange,提问作者Nested Gateway

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:20:55