【问题标题】:How to make react native app save the language when changed from the app with i18next?使用 i18next 从应用程序更改时,如何使反应本机应用程序保存语言?
【发布时间】:2021-05-19 11:23:13
【问题描述】:

我在 react native 中使用 i18next 以在应用程序中使用多种语言: 用户可以通过单击按钮从应用程序更改语言 在这个按钮中,我做了一个动作来设置 AsyncStorage 中的语言, 在 i18next 初始化文件中,我想使用 AsyncStorage 的值,但它没有更改它,因为 AsyncStorage 它需要异步和等待,因此更改值需要很长时间, 这是代码:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import English from '../Translation/Languages/English.json';
import Spanish from '../Translation/Languages/Spanish.json';
import Arabic from '../Translation/Languages/Arabic.json';
import AsyncStorage from '@react-native-async-storage/async-storage';

let language = null;

const changeLanguage = async () => {
try {
    const Lang = await AsyncStorage.getItem('Language');
    if (Lang !== null) {
        language = Lang;
    }
}
catch (error) {
    console.log("Error ", error)
}
};

changeLanguage();

i18n
.use(initReactI18next)
.init({
    lng: language,
    fallbackLng: 'en',
    resources: {
        en: English,
        es: Spanish,
        ar: Arabic
    }
});

export default i18n;

【问题讨论】:

    标签: react-native localization i18next asyncstorage react-i18next


    【解决方案1】:

    查看此medium-post 以获取工作示例...

    Github 回购 https://github.com/hend-elsahli/ReactNativeLocalization

    使用languageDetector

    i18n
      .use(languageDetector)
      .init(...)
    
    const languageDetector = {
      init: Function.prototype,
      type: 'languageDetector',
      async: true, // flags below detection to be async
      detect: async callback => {
        const selectedLanguage = await AsyncStorage.getItem('Language');
        /** ... */
        callback(selectedLanguage);
      },
      cacheUserLanguage: () => {},
    };
    

    【讨论】:

    • 我将很快发布一篇带有工作示例的中等博客文章......这不适合 SO-answer
    • @SharifAl-Hayek 一个工作示例应用程序现已在上述媒体帖子中提供......
    • 有没有办法添加默认语言?
    • @OliverD 是的...使用.init({ fallbackLng: 'en',
    • @HendEl-Sahli 你能查一下this吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多