Menu

cacheLife

cacheLife 选项允许你在组件或函数内使用 cacheLife 函数时,以及在 use cache 指令的作用域内,定义自定义缓存配置文件

用法

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

next.config.ts
TypeScript
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  cacheComponents: true,
  cacheLife: {
    blog: {
      stale: 3600, // 1 小时
      revalidate: 900, // 15 分钟
      expire: 86400, // 1 天
    },
  },
}
 
export default nextConfig

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

app/actions.ts
TypeScript
import { cacheLife } from 'next/cache'
 
export async function getCachedData() {
  'use cache'
  cacheLife('blog')
  const data = await fetch('/api/data')
  return data
}

参考

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

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