跳到內容

cacheTag

此功能目前在 Canary 管道中提供,並且可能會有所變動。請升級 Next.js 來試用,並在 GitHub 上分享您的意見回饋。

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')
}