【问题标题】:React-router server side match translated routes?React-router 服务器端匹配翻译的路由?
【发布时间】:2017-07-30 09:24:54
【问题描述】:

我正在使用 react-router 进行服务器端渲染,并且我将语言环境信息存储在 locales.json 文件中。区域信息仅在 api 调用响应后设置,其中包括当前语言,即'GB', 'NO', 'FR', etc.,然后完成服务器响应并以正确的语言将所有内容发送到客户端。

但是,我使用的是react-router match 方法:

match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { ... }

...我需要 routes 基于 api 响应中的语言,即

// Route
<Route path={`:storeId/${locales[language].path}`} />

// locale.json
{
  "GB": {
    "path": "contact"
  },
  "NO": {
    "path": "kontakt"
  }
}

这种方法可行吗?这就像我需要在进行 api 调用后定义路由,但要进行 api 调用,我需要定义路由。

【问题讨论】:

    标签: reactjs internationalization react-router locale universal


    【解决方案1】:

    是的,我没有具体尝试过您的示例,但绝对可以从 api 响应定义路由并将其传递给“匹配”函数。

    您可以尝试以下方法:

    function handleServerRendering(req, res) {
    
      axios.get('http://localhost:3001/myCutomeRoutes')
       .then(function(response){
    
         const myRoutes = {
           routes: response.data,
           location: req.url
         }
    
         match(myRoutes, function(error, redirectLocation, routeContext) {
          // WRITE YOUR CODE IN HERE...
         })
       })
       .catch(function(err){
         console.log('error', err);
       })
    }
    

    如您所见,您首先进行 API 调用,然后将 response.data 传递给“myRoutes”常量内的路由

    【讨论】:

      猜你喜欢
      • 2016-11-17
      • 2016-12-29
      • 2015-04-17
      • 2015-12-23
      • 2016-09-02
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 2016-06-01
      相关资源
      最近更新 更多