首页 > 解决方案 > 我可以在 i18next 的(异步)初始化之前使用 i18next-browser-languageDetector

问题描述

我正在使用i18next并且i18next-browser-languageDetector喜欢这样:

await (i18next
  .use(initReactI18next)
  .use(LanguageDetector)
  .init({
    resources,

    fallbackLng: process.env.DEV ? 'dev' : DEFAULT_LANGUAGE,

    debug: Boolean(process.env.DEV),

    returnObjects: true,

    interpolation: {
      escapeValue: false,
    },

    detection: {
      // Order and from where user language should be detected:
      order: ['localStorage', 'cookie', 'navigator'],

      // Keys or params to lookup language from:
      lookupLocalStorage: I18N_LANGUAGE_KEY,
      lookupCookie: I18N_COOKIE_KEY,

      // Cache user language on:
      caches: ['localStorage', 'cookie'],

      // Only detect languages that are in the whitelist:
      checkWhitelist: true,
    },
  }));

现在检测是在i18next库的初始化阶段进行的,这是异步的,所以如果我想检查已检测到的语言 ( i18next.language),我需要等待它完成。

问题是我需要在i18next加载资源之前检测语言,以便在向后端发出任何请求之前设置Accept-Language标头。axios

我知道我可以只阅读localStoragecookies或者navigator我自己,但如果可能的话,我想使用已经内置的功能i18next-browser-languageDetector

标签: javascriptreactjsi18nexti18next-browser-languagedetector

解决方案


推荐阅读