【发布时间】:2017-09-05 08:33:16
【问题描述】:
在漂亮的 URL 中使用 react-router 的最佳方式是什么?
所有 URL 都存储在 DB 中(总量约为 400,000)。
当我点击链接时,我需要通过AJAX 请求解析从服务器渲染的组件并渲染它。
谢谢!
【问题讨论】:
标签: reactjs react-router single-page-application react-router-redux
在漂亮的 URL 中使用 react-router 的最佳方式是什么?
所有 URL 都存储在 DB 中(总量约为 400,000)。
当我点击链接时,我需要通过AJAX 请求解析从服务器渲染的组件并渲染它。
谢谢!
【问题讨论】:
标签: reactjs react-router single-page-application react-router-redux
React 路由器可以采用数据库驱动的动态值。
例如,如果你有一个产品数据库,你可以有一个这样的链接:
<Link to="/products/1234/product_name">Product</Link>
你的组件会这样定义:
<Route path="/products/:id/:url_title" component={Products} />
【讨论】:
/buy-iphone7-red 或 /buy-apple-macbook-retina-13。
<Route path="/:url_title" component={Post} />
DB 中有400,000 URLs。这不是一个好主意。我发布了一个解决此问题的答案。谢谢!
我找到了问题的答案。使用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 />作为第二个参数。
【讨论】:
axios.request({url: '/you-api-endpoint'}).then(/* rest code */)