更改语言时如何翻译位置 URL?

Seb*_*nes 7 localization internationalization i18next react-router react-i18next

我目前在网站的本地化过程中遇到了障碍。使用 i18next,我们的所有路由都会被翻译,并且默认语言会从 URL 中删除区域设置路径。

换句话说:
/accueil -> /en/home
/produits -> /en/products
等等...

我的问题是,当我更改语言时,网址不跟随(这是预期的,因为 i18next 不直接与反应路由器对话)。

i18下一个配置:

i18n
  .use(detector)
  .use(initReactI18next)
  .init({
    whitelist: ['fr', 'en'],
    fallbackLng: 'fr',
    defaultNS: 'common',

    detection: {
      lookupFromPathIndex: 0,
      checkWhitelist: true
    },

    interpolation: {
      escapeValue: false
    },

    resources: {
      en: {
        routes: enRoutes,
        [...]
      },
      fr: {
        routes: frRoutes,
        [...]
      }
    }
  });

Run Code Online (Sandbox Code Playgroud)

fr/routes.json:

{
  "home": "/accueil",
  "products": "/produits",
  [...]
}
Run Code Online (Sandbox Code Playgroud)

en/routes.json:

{
  "home": "/en/home",
  "products": "en/products",
  [...]
}
Run Code Online (Sandbox Code Playgroud)

app.jsx 中的路由器部分:

<Router forceRefresh>
  <Switch>
    <Route path={`/:locale(en|fr)?${t('routes:home')}`} component={HomeComponent} />
    <Route path={`/:locale(en|fr)?${t('routes:products')}`} component={ProductsComponent} />
  </Switch>
</Router>
Run Code Online (Sandbox Code Playgroud)

使用以下配置,页面渲染不会出现问题,并且在调用 i18n.changeLanguage 时可以轻松翻译,但 url 不会随之更改。我到处搜索过,似乎找不到在语言更改后翻译网址的首选方法。

我还想处理用户直接在浏览器 URL 字段中手动更改区域设置的情况。

我尝试过更新 i18next 中“languageChanged”事件的 url,但找到当前页面的密钥会增加很多复杂性。

提前感谢您提供的任何帮助。

Seb*_*nes 2

我终于找到了一种简单干净的方法来改变路线,同时也改变语言。

  const changeLanguage = (nextLanguage) => {
    const routes = i18n.getResourceBundle(i18n.language, 'routes');
    const currentPathname = window.location.pathname.replace(/\/+$/, '');
    const currentRouteKey = Object.keys(routes).find((key) => routes[key] === currentPathname);

    window.location.replace(t(`routes:${currentRouteKey}`, { lng: nextLanguage }));
  };
Run Code Online (Sandbox Code Playgroud)

我还需要更改 i18next 检测选项,如下所示:

detection: {
  order: ['path', ...otherMethods]
  lookupFromPathIndex: 0,
  checkWhitelist: true
},
Run Code Online (Sandbox Code Playgroud)

我现在可以在任何地方安全地调用此changeLanguage 包装器,它将处理语言更改(如果它不是 url 的一部分,则变为默认值)和路由更改。