【问题标题】:react-i18next: How can I get text in a language, that is not my current selected one?react-i18next:如何获取不是我当前选择的语言的文本?
【发布时间】:2021-06-14 13:44:06
【问题描述】:

我有以下问题:我使用 react 和 i18next 并且还使用 i18next-backend 加载我的翻译文件。我有一个 languageSwitcher,我不仅要使用它来更改语言,还要使用它来更改 URL。 但我需要在更改语言之前访问新语言的命名空间“路由”。 我该怎么做?

这是我的 i18n 配置:

i18n
  .use(initReactI18next)
  .use(detector)
  .use(HttpApi)
  .init({
    defaultNS: 'routes',
    fallbackLng: ['de'],
    supportedLngs: ['de', 'en'],

    detection: {
      order: ['path'],
      lookupFromPathIndex: 0,
    },
    backend: {
      loadPath: '/locales/{{lng}}/{{ns}}.json',
    },

    keySeparator: false,

    interpolation: {
      format,
    },
  });

export default i18n;

我的语言选择器使用这个功能:

changeLanguage = (ln) => {
  const routes = i18n.getResourceBundle(i18n.language, 'routes');
  const currentPathname = window.location.pathname.replace(/\/+$/, '');
  let currentRouteKey = Object.keys(routes).find((key) => routes[key] === currentPathname);
  if (ln === 'en' && currentPathname === '') {
    currentRouteKey = '/en';
  }
  window.location.replace(this.props.t('routes:' + currentRouteKey, { lng: ln }));
};

德语是我的后备语言,当我从应用程序的英文版本开始时,语言更改有效,但当我从德语版本开始时,它不起作用。我猜那是因为没有加载英文文件。如何触发此文件?

【问题讨论】:

    标签: reactjs i18next react-i18next


    【解决方案1】:

    代替整页重新加载(使用location.replace),您可以触发i18next.changeLangauge 更改语言,在后台lib 将加载缺少的语言,然后您可以使用History Api 更改URL。

    // pseudo code
    
    changeLanguage = (ln) => {
      i18n.changeLanguage(lng, (err) => {
          if (err) {
            // handle language change error
          }
    
          const pathnameParts = window.location.pathname.split("/");
          const currentLangPath = pathnameParts[1]; // skips the first slash
          let newPathnameParts = pathnameParts;
          if (i18n.options.supportedLngs.includes(currentLangPath)) {
            newPathnameParts = newPathnameParts.slice(2); // removes the lang part
          }
    
          newPathnameParts = [lngSubPaths[lng]].concat(
            newPathnameParts.filter(Boolean)
          );
    
          const newPathname = newPathnameParts.join("/");
    
          if (newPathname !== window.location.pathname) {
            window.history.pushState(null, "", newPathname);
          }
        });
    };
    

    工作codesandbox example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      相关资源
      最近更新 更多