Skip to main content

unstable_cache

unstable_cache 允许你缓存昂贵操作的结果(例如数据库查询),并在多个请求中重用它们。

¥unstable_cache allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.

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 并将所需的动态数据作为参数传入。

¥Good to know: Accessing dynamic data sources such as headers or cookies inside a cache scope is not supported. If you need this data inside a cached function use headers outside of the cached function and pass the required dynamic data in as an argument.

警告:该 API 不稳定,将来可能会发生变化。如果需要,随着此 API 的稳定,我们将提供迁移文档和代码模块。

¥Warning: This API is unstable and may change in the future. We will provide migration documentation and codemods, if needed, as this API stabilizes.

参数

¥Parameters

const data = unstable_cache(fetchData, keyParts, options)()
  • fetchData:这是一个异步函数,用于获取你想要缓存的数据。它必须是一个返回 Promise 的函数。

    ¥fetchData: This is an asynchronous function that fetches the data you want to cache. It must be a function that returns a Promise.

  • keyParts:这是一个标识缓存键的数组。它必须包含全局唯一的值,这些值共同标识正在缓存的数据的键。缓存键还包括传递给函数的参数。

    ¥keyParts: This is an array that identifies the cached key. It must contain globally unique values that together identify the key of the data being cached. The cache key also includes the arguments passed to the function.

  • options:这是一个控制缓存行为方式的对象。它可以包含以下属性:

    ¥options: This is an object that controls how the cache behaves. It can contain the following properties:

    • tags:可用于控制缓存失效的标签数组。

      ¥tags: An array of tags that can be used to control cache invalidation.

    • revalidate:缓存应重新生效之前的秒数。省略或传递 false 无限期地缓存或直到调用匹配的 revalidateTag()revalidatePath() 方法。

      ¥revalidate: The number of seconds after which the cache should be revalidated. Omit or pass false to cache indefinitely or until matching revalidateTag() or revalidatePath() methods are called.

返回

¥Returns

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

¥unstable_cache returns a function that when invoked, returns a Promise that resolves to the cached data. If the data is not in the cache, the provided function will be invoked, and its result will be cached and returned.

版本历史

¥Version History

版本变化
v14.0.0unstable_cache 推出。