全书目录

第五篇:Next.js 完全指南 —— 商业综合体宇宙

第九章:缓存与重验证 —— 这座楼不是每分钟都要全量重装

1 分钟 334 字 第 120 / 962 个阅读单元

Next.js 的缓存体系到 2026 这一版,已经不是“背一个 ISR 名词”就能讲明白了。
更实用的记法是:

  • 哪些结果值得复用
  • 什么时候该重新算
  • 数据改完后,哪些页面该失效
#1. 入门先记住两个动作
  • revalidatePath('/products')
  • revalidateTag('products') / updateTag('products')

大白话就是:

  • 按路径让某页或某段结果作废
  • 按标签让一批相关内容作废或更新
#2. Cache Components 是更“显式”的缓存做法

如果你启用 Cache Components,某些函数或组件可以明确声明自己可缓存。

tsx
// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  cacheComponents: true,
};

export default nextConfig;
tsx
// app/products/data.ts
import { cacheLife } from 'next/cache';

export async function getProducts() {
  'use cache';
  cacheLife('hours');

  return [
    { id: 'p1', name: '键盘' },
    { id: 'p2', name: '显示器' },
  ];
}

然后在写入动作里让它失效:

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

import { revalidatePath } from 'next/cache';

export async function createProduct(formData: FormData) {
  const name = String(formData.get('name') ?? '');

  // await db.product.create({ data: { name } });

  revalidatePath('/products');
}
#3. 先别把缓存想玄学了

你可以把它理解成商场仓储系统:

text
取货结果
├── 如果足够稳定,就放进仓库复用
├── 如果刚改过库存,就通知相关货架重算
└── 不要每来一个顾客就把整栋楼重新装修一遍