跳至內容
API 參考函式unstable_cache

unstable_cache

此 API 目前不穩定,後續可能會有變動。

unstable_cache 允許您快取高成本操作(例如資料庫查詢)的結果,並在多個請求中重複使用它們。

import { getUser } from './data';
import { unstable_cache } from 'next/cache';
 
const getCachedUser = unstable_cache(
  async (id) => getUser(id),
  ['my-app-user']
);
 
export default async function Component({ userID }) {
  const user = await getCachedUser(userID);
  ...
}

注意事項:

  • 在快取作用範圍內存取動態資料來源(例如 headerscookies)是不支援的。如果您需要在已快取的函式內使用這些資料,請在已快取的函式外部使用 headers,並將所需的動態資料作為參數傳入。
  • 此 API 使用 Next.js 內建的 資料快取 來在請求和部署之間保存結果。

警告:此 API 不穩定,未來可能會有所變動。隨著此 API 趨於穩定,我們將會提供遷移文件和程式碼修改工具(如果需要)。

參數

const data = unstable_cache(fetchData, keyParts, options)()
  • fetchData:這是一個非同步函式,用於擷取您想要快取的資料。它必須是一個回傳 Promise 的函式。
  • keyParts:這是一個額外的鍵值陣列,用於進一步識別快取。預設情況下,unstable_cache 已經使用參數和函式的字串化版本作為快取鍵值。在大多數情況下,它是可選的;只有在您使用外部變數而未將其作為參數傳遞時才需要使用它。但是,如果您沒有將函式中使用的閉包作為參數傳遞,則務必將其加入。
  • options:這是一個控制快取行為的物件。它可以包含以下屬性:
    • tags:可用於控制快取失效的標籤陣列。Next.js 不會使用它來唯一識別函式。
    • revalidate:快取應重新驗證的秒數。省略或傳遞 false 可以無限期地快取,或直到呼叫匹配的 revalidateTag()revalidatePath() 方法為止。

回傳值

unstable_cache 會回傳一個函式,當這個函式被呼叫時,它會回傳一個 Promise,該 Promise 會解析為快取的資料。如果快取中沒有資料,則提供的函式將會被呼叫,其結果將會被快取並回傳。

範例

app/page.tsx
import { unstable_cache } from 'next/cache'
 
export default async function Page({ params }: { params: { userId: string } }) {
  const getCachedUser = unstable_cache(
    async () => {
      return { id: params.userId }
    },
    [params.userId], // add the user ID to the cache key
    {
      tags: ['users'],
      revalidate: 60,
    }
  )
 
  //...
}

版本歷史

版本變更
v14.0.0新增 unstable_cache