cacheTag

cacheTag 函数允许您为缓存数据添加标签,以便按需使其失效。通过将标签与缓存条目关联,您可以有选择地清除或重新验证特定缓存条目,而不会影响其他缓存数据。

使用方法

要使用 cacheTag,请在 next.config.js 文件中启用 dynamicIO 标志

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    dynamicIO: true,
  },
}

export default nextConfig

cacheTag 函数接受单个字符串值或字符串数组。

import { unstable_cacheTag as cacheTag } from 'next/cache'

export async function getData() {
  'use cache'
  cacheTag('my-data')
  const data = await fetch('/api/data')
  return data
}

然后,您可以在另一个函数中使用 revalidateTag API 按需清除缓存,例如在 路由处理器服务器操作 (Server Action) 中:

'use server'

import { revalidateTag } from 'next/cache'

export default async function submit() {
  await addPost()
  revalidateTag('my-data')
}

须知事项

  • 幂等标签:多次应用相同的标签不会产生额外效果。
  • 多个标签:您可以通过向 cacheTag 传递数组来为单个缓存条目分配多个标签。
cacheTag('tag-one', 'tag-two')

示例

为组件或函数添加标签

通过在缓存函数或组件中调用 cacheTag 来为缓存数据添加标签:

import { unstable_cacheTag as cacheTag } from 'next/cache'

interface BookingsProps {
  type: string
}

export async function Bookings({ type = 'haircut' }: BookingsProps) {
  'use cache'
  cacheTag('bookings-data')

  async function getBookingsData() {
    const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
    return data
  }

  return //...
}

从外部数据创建标签

您可以使用异步函数返回的数据为缓存条目添加标签。

import { unstable_cacheTag as cacheTag } from 'next/cache'

interface BookingsProps {
  type: string
}

export async function Bookings({ type = 'haircut' }: BookingsProps) {
  async function getBookingsData() {
    'use cache'
    const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
    cacheTag('bookings-data', data.id)
    return data
  }
  return //...
}

使带标签的缓存失效

使用 revalidateTag,您可以在需要时使特定标签的缓存失效:

'use server'

import { revalidateTag } from 'next/cache'

export async function updateBookings() {
  await updateBookingData()
  revalidateTag('bookings-data')
}

On this page