# General Translation React SDKs (gt-react, gt-next, gt-react-native): Pages Router 区域设置路由 URL: https://generaltranslation.com/zh/docs/react/nextjs/pages-router-middleware.mdx --- title: Pages Router 区域设置路由 description: 如何在 Pages Router 中使用 General Translation 配置 Next.js 国际化路由。 related: links: - /docs/react/nextjs-pages-router-quickstart - /docs/react/nextjs/pages-router-static-site-generation - /docs/react/nextjs/config --- Pages Router 使用 Next.js 国际化路由解析本地化 URL,并将当前区域设置传递给 `gt-next`。路由仍保留在 `pages` 下的常规位置。 ## 配置区域设置路由 [#configure-routing] 将区域设置配置从 `gt.config.json` 导入 `next.config.ts`。`locales` 数组必须包含 `defaultLocale`: ```json title="gt.config.json" { "defaultLocale": "en", "locales": ["en", "es", "fr"] } ``` ```ts title="next.config.ts" import type { NextConfig } from 'next'; import { withGTConfig } from 'gt-next/config'; import gtConfig from './gt.config.json'; const nextConfig: NextConfig = { i18n: { locales: gtConfig.locales, defaultLocale: gtConfig.defaultLocale, }, }; export default withGTConfig(nextConfig); ``` Next.js 为默认区域设置提供不带前缀的路径,其他区域设置则带有前缀。例如,英语使用 `/about`,法语使用 `/fr/about`。 将所有页面文件直接放在 `pages` 根目录下;不要添加 `[locale]` 段: `withGTServerSideProps` 和 `withGTStaticProps` 会从 Next.js 数据函数的上下文中读取区域设置。Pages Router 的区域设置路由无需 `gt-next` middleware、`proxy.ts` 或 `middleware.ts`。 ## 关联区域设置变更 [#locale-changes] 向 [`GTProvider`](/docs/react/reference/components/gt-provider) 传递符合区域设置的 `_reload` 回调,让区域设置切换通过 Pages Router 导航进行,并加载所选区域设置的页面属性: ```tsx title="pages/_app.tsx" import type { AppProps } from 'next/app'; import Router from 'next/router'; import { GTProvider, type WithGTStaticProps } from 'gt-next'; export default function App({ Component, pageProps, }: AppProps) { const { locale, translations } = pageProps; return ( { void Router.push(Router.pathname, Router.asPath, { locale: nextLocale, }); }} > ); } ``` 对于服务器端渲染页面,请改用 `WithGTServerSideProps`。该回调会用 Pages Router 导航替代 provider 默认的整页刷新。 ## 区域设置检测的工作方式 [#locale-detection] Next.js 会在运行 `getServerSideProps` 或 `getStaticProps` 之前解析请求区域设置: * `/fr/about` 这类区域设置前缀会将 `context.locale` 设为 `fr`。 * `NEXT_LOCALE` cookie 会存储用户偏好,并可将未带前缀的请求重定向。 * 未存储偏好时,可根据浏览器语言偏好选择区域设置。 * 当没有其他已配置的区域设置匹配时,将使用 `defaultLocale`。 在 `nextConfig.i18n` 中设置 `localeDetection: false` 可禁用基于浏览器和 cookie 的自动重定向。带区域设置前缀的路由和符合区域设置的路由器导航仍可正常工作。 **v11.1.3 中的变更:**Pages Router 设置现在使用 Next.js 国际化路由,而不再使用 `gt-next` middleware 和 `pages/[locale]` 段。当 Next.js 未提供 `context.locale` 时,现有的请求检测仍会作为兼容性后备机制。 ## Next steps - /docs/react/nextjs-pages-router-quickstart - /docs/react/nextjs/pages-router-static-site-generation - /docs/react/nextjs/config