2017-05-16 108 views
3

我遇到了在我的世博会应用程序中实例化I18n的问题。问题的TL; DR是需要翻译的组件在之前呈现如何在React Native Expo应用程序中集成i18n-js

Expo.Util.getLocaleAsync() 

返回并设置区域设置。我无法弄清楚如何最好地设置它。到目前为止,我有一个I18n实例的文件,然后导入到我的应用程序的其他任何地方。它看起来是这样的:

import Expo from 'expo'; 
import I18n from 'i18n-js'; 
import english from './resources/strings/en'; 
import danish from './resources/strings/da'; 

I18n.defaultLocale = 'en-GB'; 
I18n.fallbacks = true; 

I18n.initAsync = async() => { 
    var locale = 'en-GB'; 
    try { 
    locale = await Expo.Util.getCurrentLocaleAsync(); 
    } catch (error) { 
    console.log('Error getting locale: ' + error); 
    } 

    I18n.locale = locale ? locale.replace(/_/, '-') : ''; 
}; 

I18n.translations = { 
    en: english, 
    da: danish, 
}; 

export default I18n; 

然后,在我的根应用程序组件,我做到以下几点:从 './src/i18n'

进口的I18n;

class App extends React.Component { 
    async componentWillMount() { 
    console.log('Current locale (main1): ' + I18n.currentLocale()); 
    try { 
     await I18n.initAsync(); 
    } catch (error) { 
     console.log('Error setting locale ' + error); 
    } 

    console.log('Current locale (main2): ' + I18n.currentLocale()); 
    } 

    render() { 
    return <AppContainer />; 
    } 
} 

Expo.registerRootComponent(App); 

日志声明预期值 - 首先是默认语言环境,然后是main2中更新的语言环境。问题是在做出更改之前,第一个语言环境呈现了子视图,我不明白为什么?

我想不出更好的方式来做到这一点,任何想法/提示将非常:-)

+0

后一些更多的搜索,似乎使componentWillMount()一个同步并不一定等待等待返回,正如Flow为我指示的那样。请参阅此问题中的讨论:https://github.com/facebook/flow/issues/1803。这意味着这种策略是不可行的,否则就不得不做。如何,我还不知道:-) – jhm

回答

1

理解,这可能是你的解决方案:https://github.com/xcarpentier/ex-react-native-i18n

+0

嘿马蒂,感谢您的建议:-)我确实发现了同样的回购,但1.它几乎使用相同的方法,因此会有同样的问题,2。我不想为我的项目使用分叉派生,而是想出如何更好地实现原始的,更好支持的项目。看看他在index.js中的代码,他正在做同样的事情AFAIK :-) – jhm

+0

因此,你已经使你的'componentWillMount()'异步,并且你调用'setLocale()'之前等待? – MattyK14

+1

正确,更新了问题以显示代码的调用方式:-) – jhm

2

这是什么工作我:

main.js

import I18n from 'react-native-i18n'; 

class App extends React.Component { 
    state = { 
    appIsReady: false, 
    } 

    async componentWillMount() { 
    await I18n.initAsync(); 
    this.setState({appIsReady: true}); 
    } 

    render() { 
    if (!this.state.appIsReady) { 
     return (
      <AppLoading /> 
    ); 
    } 
    return ( 
     <RootComponent> 
    ); 
) 

,并在一些组件:

import I18n from '../i18n'; 

    render() { 
    return (
     <View> 
      <Text>{I18n.t('favorites')}</Text> 
      <Text>{I18n.locale}</Text> 
     </View> 
    ) 
    } 

而且从根目录,我创建i18n/index.js

import I18n from 'react-native-i18n'; 

I18n.fallbacks = true; // let 'en-GB' fallback to 'en' if not found 
I18n.translations = { 
    'en': require('./en.json'), 
    'nl': require('./nl.json'), 
} 

export default I18n; 

i18n/nl.json我最初的荷兰语翻译文件:

{ 
    favorites: 'Jouw Favorieten', 
} 

我在package.json有这样的:

"react-native-i18n": "git+https://github.com/xcarpentier/ex-react-native-i18n.git", 
相关问题