React Native i18n在应用程序加载时设置默认语言



我有一个简单的应用程序,我使用i18next在我的应用程序中应用翻译。

这是我的i18next代码:
import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import en from './en/en.json';
import ar from './ar/ar.json';
import he from './he/he.json';
import AsyncStorage from '@react-native-async-storage/async-storage';


const getDefaultLang = async () => {

const storedLang = await AsyncStorage.getItem('currentLnaguage');
console.log(storedLang+"aaa");
/*if(storedLang!= null){
i18n.defaultLocale = storedLang;
i18n.locale = storedLang;
i18n.fallbacks = true;
}*/
return i18n
.use(initReactI18next) 
.init({
resources: {
en: en,
ar: ar,
he: he
},
//lng: storedLang ? storedLang : 'ar', 
lng: storedLang || "ar",
interpolation: {
escapeValue: false, 
},
fallbackLng: ['en', 'ar','he'],
});
};
export default getDefaultLang();

,这是我的主要应用程序文件代码:

/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
/*
import React from 'react';
import {Text} from 'react-native';
//import {SignUpScreen} from './src/components/PlayAround/ResponsiveLayout';
import {HomeScreen} from './src/screens/HomeScreen';


function App (props){
return(
<HomeScreen />
);
}



export default App;
*/
import React,{useState,useEffect} from 'react';
import  './translations/i18n';
import {View, Text,Pressable} from 'react-native';
import {useTranslation} from 'react-i18next';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {HomeScreen} from './src/screens/HomeScreen';
import {LANG_DIR} from './src/const';
import 'intl-pluralrules';

function App(props){

const {t, i18n} = useTranslation();
const [currentLanguage,setLanguage] =useState('ar');

React.useEffect(()=>{
AsyncStorage.getItem('currentLnaguage').then(val => {
//changeLanguage(val);

});
},[]);
//console.log(currentLanguage);

const changeLanguage = value => {

AsyncStorage.setItem('currentLnaguage',value);
i18n
.changeLanguage(value)
.then(() => setLanguage(value))
.catch(err => console.log(err));

};
//AsyncStorage.clear();
return (
<HomeScreen buttonTitle={t('ordernow')} deliveryText={t('delivery')} />

);
};
export default App;

我的问题是当我启动应用程序时,没有加载默认语言,当我重新加载模拟器时,语言被加载。

我试着用钩子,但是没有成功。

帮忙吗?

如果使用阿拉伯语作为默认语言在你的应用程序

React.useEffect(()=>{
(async () => {
const storedLang = await AsyncStorage.getItem('currentLnaguage');
const newDefaultLang = storedLang || "ar" // or Change ar with the default language 
i18n.locale = newDefaultLang 
changeLanguage(newDefaultLang);
});
})()
},[]);

如果您想使用作为默认设备语言在你的应用程序

React.useEffect(()=>{
(async () => {
const storedLang = await AsyncStorage.getItem('currentLnaguage');
const newDefaultLang = storedLang || i18n.locale
i18n.locale = newDefaultLang 
changeLanguage(newDefaultLang)
});
})()
},[]);

相关内容

  • 没有找到相关文章

最新更新