2017-03-09 51 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」恆