2017-03-09 54 views
0

我正在使用react-router进行服务器端渲染,并且我的区域设置信息存储在locales.json文件中。语言环境信息仅在来自api调用的响应之后设置,该响应包括当前语言,即'GB', 'NO', 'FR', etc.,然后完成服务器响应,并且以正确语言向客户端发起一切。React-router服务器端匹配转换后的路由?

不过,我使用的是react-routermatch方法:

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调用,我需要定义路由。

回答

0

是的,我没有具体地尝试过你的例子,但是可以从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”恒