【问题标题】:Change the URL path using I18next-react使用 I18next-react 更改 URL 路径
【发布时间】:2022-04-12 20:19:04
【问题描述】:

您好,选择新语言后,我无法更改 href 路径(URL)


import i18n from 'i18next';
import { useTranslation, initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import I18NextHttpBackend from 'i18next-http-backend';

i18n.on('languageChanged', function (lng) {
  
  if (lng === i18n.options.fallbackLng[0]) {
    if (window.location.pathname.includes('/' + i18n.options.fallbackLng[0])) {
      const newUrl = window.location.pathname.replace(
        '/' + i18n.options.fallbackLng[0]
      );
      window.location.replace(newUrl);
    }
  }
});

i18n
  .use(I18NextHttpBackend)
  .use(LanguageDetector)
  .use(initReactI18next) 
  .init({
    fallbackLng: ['en'], 
    whitelist: ['en', 'de', 'it', 'es'],
    detection: {
      order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'],
      caches: ['cookie'],
      lookupFromPathIndex: 0,
      checkWhitelist: true,
    },
    backend: {
      loadPath: '/localization/{{lng}}/translation.json',
    },
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;

我得到了 example.com/undefined/page1

我用这种方式将语言路径导入到Href

export const baseUrl = i18n.language === 'en' ? '' : '/' + i18n.language;

还有链接<a>home</a>

 <a className='item'  href={baseUrl + '/'} >  Home </a>

【问题讨论】:

    标签: javascript reactjs i18next react-i18next i18next-browser-languagedetector


    【解决方案1】:

    我们创建了一个LanguageChanger 组件。 handleClick 函数可确定您所说的 url 和更新,但 on LanguageChanged 不提供与 imo 相同的灵活性。

    我已经包含了两个版本的newUrl。首先,网址中不存在en。其次,如果网址中存在languageCode

      /**
       * Handles the language change
       * @param code - updated language
       * @global lang - current set language in state
       */
      let handleChange = (code) => {
        if (lang !== code) {
          // v1 - below lines since 'en' is not present in the url as your baseUrl definition
          let newUrl;
          if (lang === "en") {
            newUrl = window.location.pathname.replace(`/`, `/${code}/`);
          } else if (code === "en") {
            newUrl = window.location.pathname.replace(`/${lang}`, ``);
          } else {
            newUrl = window.location.pathname.replace(`/${lang}`, `/${code}`);
          }
          // v2 - below is the version if language is always present in the url
          // let newUrl = window.location.pathname.startsWith(`/${lang}`) ? window.location.pathname.replace(`/${lang}`, `/${code}`) : window.location.pathname.replace(`/`, `/${code}/`)
          window.location.replace(newUrl);
          localStorage.setItem("i18nextLng", code);  // this writes to the localStorage to keep the change
          setLang(code);  // this is coming from useState 
          i18n.changeLanguage(code);
        }
      };
    

    【讨论】:

      猜你喜欢
      • 2023-02-20
      • 1970-01-01
      • 2014-02-28
      • 2020-10-10
      • 1970-01-01
      • 2020-07-12
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多