【问题标题】:How to translate react-router Route paths如何翻译 react-router 路由路径
【发布时间】:2016-12-29 00:56:55
【问题描述】:

我的应用程序有多个语言环境(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>
)

如您所见,这种时髦的解决方案对应用程序的可扩展性不太好。

【问题讨论】:

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


    【解决方案1】:

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

    // 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>
    )
    

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

    // en.js
    
    module.exports = {
    //...
      "it/termini" : "en/terms",
      "it/profilo/:userId" : "en/profile/:userId"
    //...
    }
    

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

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

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

    【讨论】:

    • return (&lt;Router key={language 部分,你的意思是&lt;Route?
    • 是的,他的意思是Route
    • 使用 i18next 包,_t 函数应该这样使用:i18n.t("it/termini", { lng: language })
    猜你喜欢
    • 2017-07-30
    • 2019-09-05
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多