1

使用react-router和漂亮的URL的最佳方式是什麼? 所有網址都存儲在數據庫中(總金額約爲400,000)。 當我關注鏈接時,我需要通過AJAX請求解析來自服務器的呈現組件,並將其呈現。react-router和漂亮的網址

謝謝!

+0

可能的重複[如何實現動態路由在routes.js中生成的菜單項在側邊欄通用反應redux樣板由erikras](http://stackoverflow.com/questions/35764510/how-to-implement-dynamic -routing-in-routes-js-for-generated-menu-items-in-sideba) –

回答

0

React路由器可以採用可以由數據庫驅動的動態值。

舉例來說,如果你有一個產品數據庫,你可以有一個像這樣的鏈接:

<Link to="/products/1234/product_name">Product</Link> 

而且您的組件會這樣定義:

<Route path="/products/:id/:url_title" component={Products} /> 
+0

示例中的路徑名定義了結構。我說過這樣的路徑: '/ buy-iphone7-red'或'/ buy-apple-macbook-retina-13'。 – sergei

+0

我明白了。在這種情況下,你可能會使用類似'' – Chris

+0

我的'DB'中有'400,000''URLs'。這不是一個好主意。我發佈了一個解決這個問題的答案。謝謝! – sergei

1

我找到答案這個問題。使用react-router,您可以使用RoutegetComponent方法動態解析組件。 例如:

import ProductPage from '...' 
import CategoryPage from '...' 

const MAP_PAGE_TYPE_TO_COMPONENT = { 
    'productPage': ProductPage, 
    'categoryPage': CategoryPage 

}; 

.... 

const getComponent = (location, callback) => { 
    requestToServer(location.pathname) 
    .then(function(response){ 
     const Component = MAP_PAGE_TYPE_TO_COMPONENT[response.pageType]; 
     callback(null, <Component items = { response.items } />); 
    }) 
    .catch(callback) 
}; 

.... 

<Route 
    path='*' 
    getComponent = { getComponent } 
/> 

你應該叫callback功能與null作爲第一個參數,如果沒有錯誤,並<Component />作爲第二個參數。