首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用I18next-react更改URL路径

问使用I18next-react更改URL路径
EN

Stack Overflow用户
提问于 2021-10-03 16:30:34
回答 1查看 1.6K关注 0票数 1

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

代码语言:javascript
复制
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 1

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

代码语言:javascript
复制
export const baseUrl = i18n.language === 'en' ? '' : '/' + i18n.language;

和链接<a>home</a>

代码语言:javascript
复制
 <a className='item'  href={baseUrl + '/'} >  Home </a>
EN

回答 1

Stack Overflow用户

发布于 2022-04-12 12:19:04

我们已经创建了一个LanguageChanger组件。handleClick函数如您所述确定url和更新,但on LanguageChanged并没有提供相同的灵活性。

我已经包含了两个版本的newUrl。首先,en不存在于url中。第二,如果languageCode存在于url中。

代码语言:javascript
复制
  /**
   * 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);
    }
  };
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69426791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档