# General Translation React SDKs (gt-react, gt-next, gt-react-native): 使用缓存组件
URL: https://generaltranslation.com/zh/docs/react/nextjs/cache-components.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 如何结合使用 Next.js 缓存组件、对区域设置安全的请求函数以及本地存储的翻译。

缓存组件可以预渲染并缓存本地化的服务器端内容。区域设置、地区和翻译都必须能够在不依赖请求头、Cookie 或默认远程翻译加载器的情况下解析。

*注意：本指南适用于 Next.js 16 及更高版本，其中通过 `cacheComponents: true` 配置缓存组件。自 Next.js 16.4 起，`create-next-app` 会默认在生成的 Next.js 配置中设置 `cacheComponents` 和 `partialPrefetching`。*

## 启用缓存组件 [#enable]

在 `next.config.ts` 中启用缓存组件。请保留 Next.js 配置外层的 [`withGTConfig`](/docs/react/nextjs/config)：

```ts title="next.config.ts"
import type { NextConfig } from 'next';
import { withGTConfig } from 'gt-next/config';

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
};

export default withGTConfig(nextConfig);
```

`partialPrefetching` 需要 Next.js 16.3 或更高版本。在 Next.js 16.4 中，如果只设置了 `cacheComponents` 而未设置该选项，会发出警告。新应用请将两者都设为 `true`。

启用缓存组件后，`gt-next`：

* 需要自定义的 [`loadTranslations`](/docs/react/reference/functions/load-translations) 函数。默认的远程加载器无法安全地用于预渲染。
* 如果缺少自定义的 [`getLocale`](/docs/react/nextjs/reference/functions/get-locale) 和 [`getRegion`](/docs/react/nextjs/reference/functions/get-region) 请求函数，会发出警告。
* 禁用开发环境中运行时翻译的热重载，因为它会发起动态请求。
* 由 Next.js 负责缓存失效，而不采用常规的 General Translation 缓存过期机制。

## 处理阻塞路由 [#blocking-routes]

启用缓存组件后，如果默认区域设置检测在 `<Suspense>` 边界之外读取请求头和 cookie，`next build` 就会失败。从 Next.js 16.4 开始，`create-next-app` 默认启用缓存组件，因此 [Next.js 快速入门](/docs/react/nextjs-quickstart) 中的根布局会遇到这个问题：[`useLocale()`](/docs/react/reference/hooks/use-locale) 和 [`<GTProvider>`](/docs/react/reference/components/gt-provider) 都会在布局渲染时解析区域设置。

可在根布局中通过以下任一方式解决：

* **阻塞布局。** 从根布局导出 `instant = false`，这样其下的所有路由 (包括 not-found 页面) 都会生效。该导出需要 Next.js 16.3 或更高版本，且布局必须保持为服务端组件：

  ```tsx title="app/layout.tsx"
  export const instant = false;
  ```

* **流式传输区域设置。** 将 [`useLocale()`](/docs/react/reference/hooks/use-locale) 调用和 [`<GTProvider>`](/docs/react/reference/components/gt-provider) 移到一个子组件中，并用 `<Suspense>` 包裹该子组件。仅用边界包裹 `{children}` 是不够的：

  ```tsx title="app/layout.tsx"
  import { Suspense } from 'react';
  import { GTProvider, useLocale } from 'gt-next';

  function LocalizedShell({ children }: { children: React.ReactNode }) {
    const locale = useLocale();
    return (
      <html lang={locale}>
        <body>
          <GTProvider>{children}</GTProvider>
        </body>
      </html>
    );
  }

  export default function RootLayout({ children }: { children: React.ReactNode }) {
    return (
      <Suspense fallback={null}>
        <LocalizedShell>{children}</LocalizedShell>
      </Suspense>
    );
  }
  ```

这两种方式都会在每次请求时渲染路由。若要预渲染本地化路由，需要在不依赖请求头或 cookie 的情况下解析区域设置，具体方法见下一节。

## 解析请求值 [#request-values]

将 `[locale]` 段放在 App Router 树的根节点。根布局必须为 `app/[locale]/layout.tsx`，其上不能存在 `app/layout.tsx`。

在项目根目录中创建 `getLocale.ts`：

```ts title="getLocale.ts"
import { locale } from 'next/root-params';

export default async function getLocale() {
  return await locale();
}
```

在同一目录下创建 `getRegion.ts`。如果输出依赖地区，请返回固定地区；要禁用地区检测，则返回 `undefined`：

```ts title="getRegion.ts"
export default async function getRegion() {
  return undefined;
}
```

`withGTConfig` 会自动检测这两个文件。如果它们位于其他位置，请设置 [`getLocalePath` 和 `getRegionPath`](/docs/react/nextjs/config#request-function-paths)。

<Callout type="warn">
  请勿在这些请求函数中调用 `headers()` 或 `cookies()`。动态请求 API 无法在 `"use cache"` 边界内运行。请改为从 `next/root-params` 读取区域设置，并返回固定的区域。
</Callout>

## 将翻译存储在本地 [#local-translations]

在 Next.js 构建前生成翻译文件，然后从 bundle 中加载：

```ts title="loadTranslations.ts"
export default async function loadTranslations(locale: string) {
  try {
    const translations = await import(`./public/_gt/${locale}.json`);
    return translations.default;
  } catch {
    return {};
  }
}
```

`withGTConfig` 会在项目根目录或 `src/` 中检测 `loadTranslations.ts`。你也可以设置 [`loadTranslationsPath`](/docs/react/nextjs/config#load-translations-path)。

配置 CLI 的输出以匹配加载器，并在 `next build` 前运行 [`npx gt translate`](/docs/cli/reference/commands/translate)。有关完整工作流，请参阅[在本地存储翻译](/docs/react/guides/storing-translations)。

## 缓存翻译后的内容 [#cache-content]

在缓存函数外解析区域设置，并将其作为可序列化参数传入。函数参数会成为缓存组件缓存键的一部分，从而将不同区域设置的条目彼此隔离。

```tsx title="app/[locale]/page.tsx"
import { T } from 'gt-next';
import { getLocale } from 'gt-next/server';
import { cacheLife, cacheTag } from 'next/cache';

async function CachedContent({ locale }: { locale: string }) {
  'use cache';

  cacheLife('hours');
  cacheTag(`home-${locale}`);

  return <T>Welcome to our site</T>;
}

export default async function Page() {
  const locale = await getLocale();
  return <CachedContent locale={locale} />;
}
```

对于任何会改变渲染译文的地区或其他请求值，都应采用相同的模式。绝不要让两个区域设置共用同一个缓存条目。

## Next steps

- /docs/react/nextjs/app-router-middleware
- /docs/react/nextjs/app-router-static-site-generation
- /docs/react/nextjs/registering-request-locales
- /docs/react/nextjs/locale-alias-seo

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
