【问题标题】:Dynamic paths in react router反应路由器中的动态路径
【发布时间】:2017-07-23 14:50:02
【问题描述】:

我正在尝试将我的网站从传统的网络应用程序方法迁移到基于反应的应用程序。在这个过程中,我遇到了一个与 url 相关的问题。在我的网站中,在服务器端,我使用 Url Rewrite 功能将 url 映射到正确的控制器。但我无法弄清楚如何在反应路由器中处理这个事情。我当前的反应路由器代码如下所示

<BrowserRouter>
    <Route exact path="/" component={Home}/>
    <Route path="/black-forest" component={Product}/>
    <Route path="/cakes" component={ProductList}/>
</BrowserRouter>

我为构建原型而编写的这段代码。但理想情况下,有许多不同的 url 可以指向 ProductList 组件。同样有很多url可以指向Product组件。

例如, 以下 url 指向 ProductList 组件 - http://www.example.com/best-cakes-in-australia - http://www.example.com/cake-delivery-in-india - http://www.example.com/flowers-delivery-in-canada

总的来说,我有大约 10,000 个这样的 url,它们是使用服务器端 UrlRewrite 创建的,因此它们没有遵循特定的模式。这些 url 主要指向 ProductListProduct 组件。

如何在我的 react 路由器配置中为所有这些 url 创建路径?任何指针将不胜感激。

【问题讨论】:

  • 这对你有用吗?你有一个路由,例如&lt;Route path="/product-list/:products" component={ProductList}/&gt;,它处理http://www.example.com/product-list/best-cakes-in-australia之类的链接,你可以根据:products的值显示你需要的东西
  • 如果用户想看到澳大利亚最好的蛋糕,在这种情况下用户会看到http://www.example.com/product-list/best-cakes-in-australia而不是http://www.example.com/best-cakes-in-australia,对吗?不,这不起作用,因为它会创建新的 url,并且从 SEO 的角度来看,维护当前的 url 是至关重要的
  • 好的,所以它对我来说似乎仍然有用......当您需要展示澳大利亚最好的蛋糕并从那里推断时,只需查找 params.products === 781。
  • @KyleRichardson 我真的不明白你的意思是什么?您能否提供更多详细信息?
  • 好吧,我可能要问你几个问题。你说路线没有特定的模式。这是否意味着需要显示产品列表的 URL 不会在其 URL 中包含产品列表?如果它们都是http://www.example.com/product-list/:parameter,那么在您的ProductList 组件中,您可以使用this.props.params.product 值并根据该param.product 值显示正确的数据。

标签: reactjs react-router react-router-v4


【解决方案1】:

您可能有一个单独的端点来检查请求的 url,它返回诸如“产品”或“产品列表”之类的页面类型,并且基于此结果,您可以加载更多数据

例如,假设您有http://www.example.com/api/urlcheck

在您的路由器中:

<Route exact path="/" component={ Home } />
<Route path="/:customPath" component={ Wrapper } />

在包装器中

constructor(props) {
  super(props)
  this.state={
    componentName: null
  }
}

componentDidMount() {
  let pathname = this.props.location.pathname.substr(1)
  // alternatively you can get pathname from this.props.location.match.params.customPath
  fetch(/* send request to http://www.example.com/api/urlcheck with pathname */)
  .then((response)=>{ this.setState({componentName: response.componentName }) })
}

render (){
  const { componentName } = this.state

  if(componentName === 'Product') return <Product />
  else if(componentName === 'ProductList') return <ProductList />
}

在 Product 或 ProductList 组件中,您可以以类似的方式通过 id 或任何其他键请求特定的数据集。

但请记住,如果 SEO 是一个大块,您很可能希望进行服务器端渲染,这在上面的示例中没有发生。 componentDidMount 仅在浏览器中呈现,您必须将其替换为 componentWillMount(反应生命周期中唯一在 SSR 上运行的函数)。

SSR 有点麻烦,尤其是对于基于其他请求的响应的请求。 Redux-saga 使用这种东西让生活变得如此轻松,所以我建议在你的情况下也使用 saga 方式。

您可以查看react-saga-universal 以快速启动并运行 saga 和 SSR。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-02-05
  • 2017-12-11
  • 2022-01-17
  • 1970-01-01
  • 2019-08-03
  • 1970-01-01
  • 2021-04-20
相关资源
最近更新 更多