【问题标题】:react-router and pretty URLsreact-router 和漂亮的 URL
【发布时间】:2017-09-05 08:33:16
【问题描述】:

在漂亮的 URL 中使用 react-router 的最佳方式是什么? 所有 URL 都存储在 DB 中(总量约为 400,000)。 当我点击链接时,我需要通过AJAX 请求解析从服务器渲染的组件并渲染它。

谢谢!

【问题讨论】:

标签: reactjs react-router single-page-application react-router-redux


【解决方案1】:

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。
  • 我明白了。在这种情况下,您可能会选择&lt;Route path="/:url_title" component={Post} /&gt;
  • 我的DB 中有400,000 URLs。这不是一个好主意。我发布了一个解决此问题的答案。谢谢!
【解决方案2】:

我找到了问题的答案。使用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作为第一个参数,&lt;Component /&gt;作为第二个参数。

【讨论】:

  • Reactjs 和 axios 请求中这个问题有答案吗?而不是 AJAX? ,我有同样的问题,我想让我的反应动态 URL 可读
  • 您可以创建一个 API 来获取有关 URL 的信息,并将其与 axios 一起使用:axios.request({url: '/you-api-endpoint'}).then(/* rest code */)
猜你喜欢
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
相关资源
最近更新 更多