# gt-next: General Translation Next.js SDK: 缓存组件 URL: https://generaltranslation.com/zh/docs/next/guides/cache-components.mdx --- title: 缓存组件 description: 在 gt-next 中配置缓存组件 --- 本指南介绍如何在 gt-next 中结合使用 Next.js 缓存组件,以优化国际化应用。 *** ## 设置 如果你还没有完成这一步,请按照 [Next.js Cache Components 指南](https://nextjs.org/docs/app/getting-started/cache-components)在项目中设置缓存组件。 ### 启用缓存组件并配置请求函数 在你的 Next.js 配置中启用缓存组件,并定义使用 `next/root-params` 的自定义 `getLocale` 和 `getRegion` 请求函数,以便 gt-next 能在缓存组件内解析区域设置。 你的 `[locale]` 段必须是一个**根参数**——也就是 app 目录中的第一个动态段,并且其上方不能有 `app/layout.tsx`。根布局必须位于 `app/[locale]/` 中。 ```js title="next.config.js" const nextConfig = { cacheComponents: true, }; export default withGTConfig(nextConfig, { // 指向你的自定义请求函数 getLocalePath: './getLocale.ts', getRegionPath: './getRegion.ts', }); ``` 在项目根目录创建以下文件。它们使用 `next/root-params` 而不是 `headers()`,因此可以在 `"use cache"` 边界内使用: ```ts title="getLocale.ts" import { locale } from 'next/root-params'; export default async function getLocale(): Promise { return await locale(); } ``` ```ts title="getRegion.ts" export default async function getRegion(): Promise { return undefined; } ``` **不要在你的 `getLocale` 或 `getRegion` 函数中使用 `headers()`。** 在 `"use cache"` 边界内调用 `headers()` 会导致构建错误。请按上文所示使用 `next/root-params`。 `experimentalLocaleResolution` 已在 gt-next@6.16.29 起弃用。它依赖不受支持的 Next.js 内部实现,在未来的 Next.js 版本中可能会失效。请改用显式的 `getLocalePath` 和 `getRegionPath` 配置。 ### 启用中间件 在[这里](/docs/next/guides/middleware)查看完整的中间件指南。 ```ts import { createNextMiddleware } from 'gt-next/middleware'; export default createNextMiddleware(); export const config = { // 匹配除 API 路由、静态文件和 Next.js 内部路径之外的所有路径 matcher: ['/((?!api|static|.*\\..*|_next).*)'] }; ``` ### 为包含可翻译内容的缓存组件添加 `locale` 参数 使用包含可翻译内容的缓存组件时,必须将 `locale` 作为参数传入。这样可确保每个区域设置都有各自的缓存条目。 ```tsx import { getLocale } from "gt-next/server" async function CachedContent({locale}: {locale: string}) { "use cache" return Hello World } export default async function Page() { const locale = await getLocale() return } ``` ## 配置注意事项 * 使用自定义 `getLocalePath` 和 `getRegionPath` 时,这些函数会负责为缓存组件解析区域设置和地区。 * `next/root-params` API 允许从组件树中的任何位置读取诸如 `[locale]` 之类的路由参数,包括在 `"use cache"` 边界内。根参数值会自动成为缓存键的一部分。 * `[locale]` 段必须是根参数 (其上方不能有 `app/layout.tsx`) 。 *** ## 后续步骤 * 如需了解更多信息,请阅读此功能的发布说明:[gt-next@6.10.0](/devlog/gt-next_v6_10_0)。