跳到内容
API 参考函数unstable_cache

unstable_cache

警告:此 API 达到稳定状态后将由 use cache 取代。

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 内置的 数据缓存 来在请求和部署之间持久化结果。

参数

const data = unstable_cache(fetchData, keyParts, options)()
  • fetchData:这是一个异步函数,用于获取您想要缓存的数据。它必须是一个返回 Promise 的函数。
  • keyParts:这是一个额外的键数组,用于进一步标识缓存。默认情况下,unstable_cache 已经使用您的函数的参数和字符串化版本作为缓存键。在大多数情况下它是可选的;只有当您使用外部变量而不将其作为参数传递时才需要使用它。但是,如果您不将闭包作为参数传递,则务必添加函数中使用的闭包。
  • options:这是一个控制缓存行为的对象。它可以包含以下属性:
    • tags:可用于控制缓存失效的标签数组。Next.js 不会用它来唯一标识函数。
    • revalidate:缓存应重新验证的秒数。省略或传递 false 可无限期缓存,或者直到调用匹配的 revalidateTag()revalidatePath() 方法。

返回

unstable_cache 返回一个函数,当调用时,该函数返回一个解析为缓存数据的 Promise。如果数据不在缓存中,则将调用提供的函数,其结果将被缓存并返回。

示例

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

版本历史

版本更改
v14.0.0unstable_cache 已引入。