我会在路由更改时动态加载页面的翻译。我使用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')
);