缓存的标记方式:标签 vs 路径
知道了怎么缓存数据之后,下一个问题是:当数据更新时,怎么告诉 Next.js "哪些缓存该失效"?
Next.js 提供了两种标记缓存的方式,它们决定了你后续失效缓存时的精准度。
按标签标记(Tags)
在 fetch 时通过 next.tags 给缓存打标签。一个请求可以打多个标签,多个请求也可以共享同一个标签:
// 文章列表——打 'posts' 标签
const posts = await fetch("https://api.example.com/posts", {
next: { tags: ["posts"] },
});
// 单篇文章——同时打 'posts' 和 'post-123' 两个标签
const post = await fetch("https://api.example.com/posts/123", {
next: { tags: ["posts", "post-123"] },
});
// 文章评论——打 'posts'、'post-123'、'comments' 三个标签
const comments = await fetch("https://api.example.com/posts/123/comments", {
next: { tags: ["posts", "post-123", "comments"] },
});
失效时可以精准控制:
updateTag("posts"); // 失效所有文章相关的缓存
updateTag("post-123"); // 只失效 ID 为 123 的文章及其评论
updateTag("comments"); // 只失效评论
按路径标记
不需要显式标记,直接通过页面路径来失效。Next.js 会失效该路径下所有关联的缓存: