问题
I am developing a multilanguage application using React, i18next
and i18next-browser-languagedetector
.
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;
And I have implemented a language selector that just changes the value in the localStorage
to what the user chose.
Is this the correct way of doing it?
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.
回答1:
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
});
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. :)
回答2:
I think you are very close. You can just set i18n
with fallback language initially. And then after loading saved language information for localstorage or localforage or whatever storage, call i18nInstance.changeLanguage(lng)
.
回答3:
@firstdoit:
Good answer with regards to automatic browser language detection. However, don't you think that, it is a better approach of having both the automatic and manual configuration availed to a user.
For instance, if one has a browser set to english, this will be ok for the automatic approach you are suggesting based on the documentation. Should a user change a page language from English to French, this doesn't affect the browser language hence keeping the site only in english because configurations are set to automatically detect browser language.
I, in turn, will give priority to the current page language:
- Either passed via parameters (/george.php?lang=fr or /fr_FR/george.php)
This will turn be passed as props to my code as a prority as follow
- var lang = this.props.lang || this.services.languageDetector.detect() || "en";
What's your take?
来源:https://stackoverflow.com/questions/35728632/react-i18next-and-correct-way-of-changing-language