Skip to content

cacheLife

cacheLife 选项允许你在组件或函数内部以及 use cache 指令 范围内使用 cacheLife 函数时定义自定义缓存配置文件。

¥The cacheLife option allows you to define custom cache profiles when using the cacheLife function inside components or functions, and within the scope of the use cache directive.

用法

¥Usage

要定义配置文件,请启用 dynamicIO 标志 并在 next.config.js 文件中的 cacheLife 对象中添加缓存配置文件。例如,blog 配置文件:

¥To define a profile, enable the dynamicIO flag and add the cache profile in the cacheLife object in the next.config.js file. For example, a blog profile:

ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    dynamicIO: true,
    cacheLife: {
      blog: {
        stale: 3600, // 1 hour
        revalidate: 900, // 15 minutes
        expire: 86400, // 1 day
      },
    },
  },
}

export default nextConfig
js
module.exports = {
  experimental: {
    dynamicIO: true,
    cacheLife: {
      blog: {
        stale: 3600, // 1 hour
        revalidate: 900, // 15 minutes
        expire: 86400, // 1 day
      },
    },
  },
}

你现在可以在组件或函数中使用此自定义 blog 配置,如下所示:

¥You can now use this custom blog configuration in your component or function as follows:

tsx
import { unstable_cacheLife as cacheLife } from 'next/cache'

export async function getCachedData() {
  'use cache'
  cacheLife('blog')
  const data = await fetch('/api/data')
  return data
}
jsx
import { unstable_cacheLife as cacheLife } from 'next/cache'

export async function getCachedData() {
  'use cache'
  cacheLife('blog')
  const data = await fetch('/api/data')
  return data
}

参考

¥Reference

配置对象具有以下格式的键值:

¥The configuration object has key values with the following format:

属性描述要求
stalenumber客户端应缓存值而不检查服务器的持续时间。可选
revalidatenumber缓存在服务器上刷新的频率;重新验证时可能会提供过时的值。可选
expirenumber在切换到动态之前值可以保持陈旧的最长持续时间。可选 - 必须比 revalidate

Next.js v15.2 中文网 - 粤ICP备13048890号