更新应用程序 React Natice 的所有屏幕中的变量
我的应用程序有法语和英语版本。我希望用户能够更改任何页面上的语言,并且当他们导航到任何其他屏幕时,我希望反映更改。
例如,我有 A.js
const A = (props) => {
const [language, setLanguage] = useState('')
return (
<View style ={styles.container}>
<Button onPress ={()=>setLanguage('french')}>{language==="french" ? changer la langue : change the language}
</Button>
</View>
)
}
Now when I go to any screen after pressing the button I want the content to be rendered in French and if I change the language in another screen I want changer la langue
to be rendered in this screen内存泄漏
const [language, setLanguage] = useState('')
const [visible, setVisible] = useState(false)
const {t} = useTranslation();
const fetchLanguage = async () =>{
try{
const currentLanguage = await AsyncStorage.getItem('language')
if (currentLanguage === null ){
setVisible(true)
}
else{
setLanguage (currentLanguage)
i18n.changeLanguage(currentLanguage)
}
}catch (e){
console.log(e)
}
}
useEffect (()=>{
fetchLanguage()
}, [])
My app is both in French and English. I want the user to be able to change the language on any page and when they navigate to any other screen I want the change to be reflected.
For instance, I have A.js
const A = (props) => {
const [language, setLanguage] = useState('')
return (
<View style ={styles.container}>
<Button onPress ={()=>setLanguage('french')}>{language==="french" ? changer la langue : change the language}
</Button>
</View>
)
}
Now when I go to any screen after pressing the button I want the content to be rendered in French and if I change the language in another screen I want changer la langue
to be rendered in this screen
Memory leakage
const [language, setLanguage] = useState('')
const [visible, setVisible] = useState(false)
const {t} = useTranslation();
const fetchLanguage = async () =>{
try{
const currentLanguage = await AsyncStorage.getItem('language')
if (currentLanguage === null ){
setVisible(true)
}
else{
setLanguage (currentLanguage)
i18n.changeLanguage(currentLanguage)
}
}catch (e){
console.log(e)
}
}
useEffect (()=>{
fetchLanguage()
}, [])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以继续创建一个上下文来手动管理它,但这就像重新创建轮子一样。
您可以立即使用 i18next 和 react-i18next 支持应用程序范围的本地化,只需最少的设置,就像下面的 React Native 一样。
然后,您可以通过 docs 中描述的简单方法在应用程序中轻松使用这些翻译,
例如
< strong>更新:让用户在应用程序内更改语言
您仍然可以使用此 i18next 让您的用户在应用程序内更改语言,只需在 i18 实例上调用一个简单的方法即可,如文档此处。
You can go ahead make a context to manage that manually however that will be something like recreating wheel.
You can right away use i18next and react-i18next to support app wide localisation with just minimal setup like below in React Native too.
Then you can easily use these translations in app via easy ways as described in the docs
Such as
Update: Let user change the language from within the app
You can still use this i18next to let your users change the language from within the app by just calling a simple method on i18 instance as documented here.