React-Router和React-Intl:有没有更好的方法来动态加载翻译的路线?

时间:2016-04-09 15:45:07

标签: javascript reactjs webpack react-router react-intl

我会在路由更改时动态加载页面的翻译。我使用onEnter为每条路线完成了它。

有没有更好的方法来实现这个?我可以避免为每条路由使用onEnter回调函数吗?

var  Root = React.createClass({       
    baseTranslations : {},

    getInitialState: function(){    
        return {
            lang: 'it',
            translations: null,
        };    
    },    

    componentWillMount: function() {    
        // load the common translation for all routes            
        this.setState({
            lang: this.getLocale().lang
        }); 
        this.loadTranslation("base");
    },

    onChangeRoute: function(nextState, replace){
        // load the specific route's translation
        this.loadTranslation(nextState.location.pathname);
    },

    getLocale: function(what){
        // return lang and user region (ex: it-IT)    
    },

    loadTranslation: function(route){    
        var lcl = route;    
        var mapping = {
            '/'     : 'home',
            'auth'  : 'dashboard'
        };

        if(route in mapping){
            lcl = mapping[route];
        }

        $.ajax({
            url: './locales/' + this.state.lang +'/' + lcl + '.json',
            dataType: "text",
        }).done(function(res) {

            if(lcl === "base"){
                this.baseTranslations = JSON.parse(res);
            }

            this.setState({
                translations: $.extend(true, this.baseTranslations, JSON.parse(res))
            });

        }.bind(this));

    },

    render: function() {
        var children;

        if (this.state.translations) {
            children = (
                <IntlProvider locale={this.state.lang} messages={this.state.translations}>
                    <Router history={browserHistory}>
                        <Route path="/" component={App}>
                            <IndexRoute component={Home}/>

                            <Route path="signup"  onEnter={this.onChangeRoute} getComponents={(location, cb) => {

                                 require.ensure([], (require) => {
                                        cb(null, require('./components/Signup.jsx'))
                                 }, "Signup")

                            }} />     

                            <Route path="*" component={NoMatch}/>
                        </Route>
                    </Router>
                </IntlProvider>
            );
        }

        return <div>{children}</div>;
    }
});


ReactDOM.render(
    <Root/>,
    document.getElementById('rct-cont')
);

0 个答案:

没有答案