2016-08-22 106 views
9

我的应用程序有多个区域设置(it,en)。如何翻译react-router路径路径

我需要翻译所有路线。比如我有条款和条件页面有路径(每个区域一个):

  • it/termini
  • en/terms

我需要的不仅仅是做一些事情,如:

// routes.js 

const routes = (
    <Route path="/" component={App}> 
    <IndexRoute component={HomePage} /> 
    <Route path="(it/termini)(en/terms)" component={TermsPage} /> 
    <Route path="*" component={NotFoundPage} /> 
    </Route> 
) 

正如您所看到的,这个时髦的解决方案对于应用程序的可伸缩性不太好。

回答

3

我现在使用路由本地化的方法就是像处理任何本地化内容一样处理它们。 在你的情况,我会做:

// routes.js 

function createRoutes(language) { 
    /* 
    You'll probably have more work to do here, 
    such as sub-routes initialization 
    component's type selection logic, etc. 

    @note: _t(key, language) is your 
      translation function 
    */ 

    return (
     <Router 
      key={language} 
      path={_t("it/termini", language)} 
      component={TermsPage} 
     /> 
    ) 
} 

let localizedRoutes = supportedLanguages.map(createRoutes) 

const routes = (
    <Route path="/" component={App}> 
    <IndexRoute component={HomePage} /> 
    {localizedRoutes} 
    <Route path="*" component={NotFoundPage} /> 
    </Route> 
) 

然后你就可以在你的翻译文件中指定它们,就像任何其他字符串,包括任何参数:

// en.js 

module.exports = { 
//... 
    "it/profilo/:userId" : "en/profile/:userId" 
//... 
} 

您也可以将它们组装之前飞您的路线已定义,并将它们关联到相应的翻译键。

这样它/末端成为你的翻译URL只是关键,你也可以使用一些不类似的底层URL像条款页面的URL

此方法还允许您区分每种语言的路线组件和/或子路线,这是额外的好处。只需在映射函数内部实现逻辑(或适用于您的应用程序的地方)。

+1

on'return( cl0udw4lk3r

+0

是的,他的意思是'Route' – Telokis