跳到主要内容

cacheTag

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

用法

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

next.config.ts
import type { NextConfig } from 'next'

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

export default nextConfig

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

app/data.ts
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 在另一个函数中按需清除缓存,例如,在 路由处理器服务器操作 中:

app/action.ts
'use server'

import { revalidateTag } from 'next/cache'

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

提示

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

示例

为组件或函数添加标签

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

app/components/bookings.tsx
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 //...
}

从外部数据创建标签

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

app/components/bookings.tsx
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,你可以在需要时使特定标签的缓存失效:

app/actions.ts
'use server'

import { revalidateTag } from 'next/cache'

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