HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

03-第 2 层:数据缓存 (Data Cache)

第 20 / 22 段:实战案例

Next.js 缓存机制全解析 · 发布 2026-02-20 · 更新 2026-11-11 · 标签:Next.js、缓存、前端架构、React

实战案例

案例:博客系统

// lib/api.ts
export async function getPosts() {
  const res = await fetch('https://api.example.com/posts', {
    next: {
      revalidate: 3600, // 每小时更新
      tags: ['posts'] // 打标签
    }
  });
  return res.json();
}

export async function getPost(id: string) {
  const res = await fetch(`https://api.example.com/posts/${id}`, {
    next: {
      revalidate: 3600,
      tags: ['posts', `post-${id}`] // 多个标签
    }
  });
  return res.json();
}

// app/actions.ts
'use server';

import { updateTag } from 'next/cache';

export async function createPost(formData: FormData) {
  // 1. 创建文章
  await db.post.create({ data: { ... } });

  // 2. 立即失效列表缓存(用户提交后立刻看到新文章)
  updateTag('posts');
}

export async function updatePost(id: string, formData: FormData) {
  // 1. 更新文章
  await db.post.update({ where: { id }, data: { ... } });

  // 2. 立即失效列表和详情缓存
  updateTag('posts');
  updateTag(`post-${id}`);
}

如果是在 Route Handler 中(比如接收 webhook),则使用 revalidateTag: