React i18next和正确的语言更改方式 [英] React i18next and correct way of changing language

查看:323
本文介绍了React i18next和正确的语言更改方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React, i18next i18next-browser-languagedetector 开发多语言应用程序.

I am developing a multilanguage application using React, i18next and i18next-browser-languagedetector.

我通过以下方式初始化i18next:

I initialize i18next the following way:

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 中的值更改为用户选择的值.

And I have implemented a language selector that just changes the value in the localStorage to what the user chose.

这是正确的方法吗?

我问,因为即使这可行,但我仍通过设置 localStorage.getItem(I18N_LANGUAGE)||来作弊"."pt" ,并且我没有按照我的意愿使用语言检测.

I ask because even though this works, I feel I am "cheating" by setting localStorage.getItem(I18N_LANGUAGE) || "pt" and that I am not using the language detection as I should.

推荐答案

根据文档a>,您无需自己指定语言:

According to the documentation, you shouldn't need to specify the language yourself:

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

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

并且根据这部分来源 i18next ,它确实使用了插件的检测功能:

And according to this piece of source in i18next, it indeed uses the detection capabilities of the plugin:

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

这是正确的方法吗?

Is this the correct way of doing it?

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

So, no, it isn't . Let the plugin do it's job. :)

这篇关于React i18next和正确的语言更改方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆