javascript - React i18next 和更改语言的正确方法

标签 javascript reactjs translation i18next

我正在使用 React、i18nexti18next-browser-languagedetector 开发多语言应用程序。

我按以下方式初始化 i18next:

i18n
  .use(LanguageDetector)
  .init({
    lng: localStorage.getItem(I18N_LANGUAGE) || "pt",
    fallbackLng: "pt",
    resources: {
      en: stringsEn,
      pt: stringsPt
    },
    detection: {
      order: ["localStorage", "navigator"],
      lookupQuerystring: "lng",
      lookupLocalStorage: I18N_LANGUAGE,
      caches: ["localStorage"]
    }
  });

export default i18n;

我已经实现了一个语言选择器,它只是将 localStorage 中的值更改为用户选择的值。

这是正确的做法吗?

我问是因为即使这有效,我觉得我通过设置 localStorage.getItem(I18N_LANGUAGE) || 是在“作弊” “pt” 并且我没有按应有的方式使用语言检测。

最佳答案

根据documentation ,您不需要自己指定语言:

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

i18next
  .use(LngDetector)
  .init({
    detection: options
  });

并根据this piece of sourcei18next中,确实使用了插件的检测能力:

if (!lng && this.services.languageDetector) lng = this.services.languageDetector.detect();

Is this the correct way of doing it?

所以,不,不是。让插件完成它的工作。 :)

关于javascript - React i18next 和更改语言的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35728632/

相关文章:

javascript - 从网站下载 Chrome 扩展程序,无需重定向到 Chrome 网上应用店页面

javascript - 图像渲染值有时会更新,有时不会

javascript - 如何解决 "Greetings, time traveller. We are in the golden age of prefix-less CSS, where Autoprefixer is no longer needed for your stylesheet."?

JavaScript 剪刀石头布游戏

c# - 是否可以在 Web App Bot 中翻译自适应卡片?

jquery - 使用 jQuery Mobile 的多语言应用程序

symfony - 如何在 Symfony 中获取所有翻译消息域

javascript - 从不同文件调用函数

css - 更改工具提示的样式 - recharts

ruby-on-rails - ruby on Rails 中的部分与 React 有什么区别?