反应路由器和漂亮的网址
react-router and pretty URLs
将 react-router
用于漂亮网址的最佳方式是什么?
所有 URL 都存储在 DB 中(总量约 400,000
)。
当我遵循 link 时,我需要通过 AJAX
请求解析要从服务器渲染的组件并渲染它。
谢谢!
React 路由器可以采用数据库驱动的动态值。
例如,如果你有一个产品数据库,你可以有这样的 Link:
<Link to="/products/1234/product_name">Product</Link>
您的组件将定义如下:
<Route path="/products/:id/:url_title" component={Products} />
我找到了问题的答案。使用 react-router
,您可以使用 Route
的 getComponent
方法动态解析组件。
例如:
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 />
。
将 react-router
用于漂亮网址的最佳方式是什么?
所有 URL 都存储在 DB 中(总量约 400,000
)。
当我遵循 link 时,我需要通过 AJAX
请求解析要从服务器渲染的组件并渲染它。
谢谢!
React 路由器可以采用数据库驱动的动态值。
例如,如果你有一个产品数据库,你可以有这样的 Link:
<Link to="/products/1234/product_name">Product</Link>
您的组件将定义如下:
<Route path="/products/:id/:url_title" component={Products} />
我找到了问题的答案。使用 react-router
,您可以使用 Route
的 getComponent
方法动态解析组件。
例如:
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 />
。