如何使用来自i18nextBrowserLanguageDetector

时间:2018-10-11 19:26:30

标签: javascript i18next

我正在尝试使用i18nextBrowserLanguageDetector检测用户的浏览器语言设置,如果我们支持他们的首选语言,则将其重定向到翻译的页面。下面的代码的第一部分似乎工作正常,并将正确地将用户的语言首选项缓存在cookie中。

import i18next from 'i18next';
import LngDetector from 'i18next-browser-languagedetector';

i18next
  .use(LngDetector)
  .init({
    detection: {
      // order and from where user language should be detected
      order: ['cookie', 'navigator', 'htmlTag', 'path'],

      // keys or params to lookup language from
      lookupCookie: LANG_COOKIE,
      lookupFromPathIndex: 0,

      // cache user language on
      caches: ['cookie']
    }
  });

但是,我遇到的问题是我想根据用户的语言设置来执行某项操作,但是好像i18next异步运行其检测代码,但没有提供我可以看到的任何回调。问题的部分原因在于他们的文档非常苗条。我要做的是在文档上添加一些代码,如下所示:

document.addEventListener('DOMContentLoaded', () => {
  const langPref = Cookies(LANG_COOKIE);
  if (!!langPref && SUPPORTED_LANGS.includes(langPref) && langPref !== currentLocale())
    window.location.href = `${location.origin}/${langPref}${location.pathname}`;
});

但是,在页面完成加载时,永远不会设置语言cookie。我可以添加一个setTimeout / Interval,但这有点笨拙且效率低下。

1 个答案:

答案 0 :(得分:1)

使用方法:

android.support.design.widget.BottomNavigationView

还使用白名单选项,因此lng始终是您支持的内容;)

相关问题