如何翻译react-router路由路径

cl0*_*k3r 11 javascript reactjs react-router redux react-intl

我的应用程序有多个语言环境(it,en).

我需要翻译所有路线.例如,我有条件和条件页面必须路径(每个区域一个):

  • 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>
)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这个时髦的解决方案对于应用程序的可伸缩性来说并不是那么好.

Dan*_*ani 5

我目前处理路线本地化的方法是像处理任何本地化内容一样处理它们。在你的情况下,我会这样做:

// 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 (
       <Route 
          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>
)
Run Code Online (Sandbox Code Playgroud)

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

// en.js

module.exports = {
//...
  "it/termini" : "en/terms",
  "it/profilo/:userId" : "en/profile/:userId"
//...
}
Run Code Online (Sandbox Code Playgroud)

您还可以在定义路线之前即时组装它们,将它们与相应的翻译键相关联。

通过这种方式,it/termini成为您翻译的 URL 的关键,您也可以使用与基础 URL 不相似的内容,例如terms-page-url

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

  • 在 `return (&lt;Router key={language` 部分,你的意思是 `&lt;Route`? (2认同)