Skip to main content

unstable_cache

在版本 15 中,我们建议改用 use cache 指令。

¥In version 15, we recommend using the use cache directive instead.

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);
...
}

很高兴知道:

¥Good to know:

  • 不支持访问缓存范围内的动态数据源,例如 headerscookies。如果你需要在缓存函数内使用此数据,请在缓存函数外部使用 headers 并将所需的动态数据作为参数传入。

    ¥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 使用 Next.js 的内置 数据缓存 在请求和部署之间持久保存结果。

    ¥This API uses Next.js' built-in Data Cache to persist the result across requests and deployments.

警告:该 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:这是一个额外的键数组,可进一步为缓存添加标识。默认情况下,unstable_cache 已经使用参数和函数的字符串化版本作为缓存键。在大多数情况下,它是可选的;你唯一需要使用它的时候是当你使用外部变量而不将它们作为参数传递时。但是,如果不将函数中使用的闭包作为参数传递,则添加它们非常重要。

    ¥keyParts: This is an extra array of keys that further adds identification to the cache. By default, unstable_cache already uses the arguments and the stringified version of your function as the cache key. It is optional in most cases; the only time you need to use it is when you use external variables without passing them as parameters. However, it is important to add closures used within the function if you do not pass them as parameters.

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

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

    • tags:可用于控制缓存失效的标签数组。Next.js 不会使用它来唯一地标识该函数。

      ¥tags: An array of tags that can be used to control cache invalidation. Next.js will not use this to uniquely identify the function.

    • 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.

示例

¥Example

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

//...
}
import { unstable_cache } from 'next/cache';

export default async function Page({ params } }) {
const getCachedUser = unstable_cache(
async () => {
return { id: params.userId };
},
[params.userId], // add the user ID to the cache key
{
tags: ["users"],
revalidate: 60,
}
);

//...
}

版本历史

¥Version History

版本变化
v14.0.0unstable_cache 推出。