React Router中的动态路径

3

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

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

我写了这段代码来构建原型模型。但理想情况下,有许多不同的网址可以指向ProductList组件。同样,有许多网址可以指向Product组件。

例如, 以下网址将指向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个此类网址,这些网址是使用服务器端UrlRewrite创建的,因此它们没有遵循任何特定的模式。这些网址大多数情况下将指向ProductListProduct组件。

我如何在我的React路由器配置中为所有这些网址创建路径? 任何提示都将不胜感激。


1
这个方案对你是否可行?例如,你有一个路由 <Route path="/product-list/:products" component={ProductList}/> 处理像 http://www.example.com/product-list/best-cakes-in-australia 这样的链接,你可以根据 :products 的值来显示所需内容。 - Kyle Richardson
如果用户想要查看澳大利亚最好的蛋糕,那么用户将会看到http://www.example.com/product-list/best-cakes-in-australia而不是http://www.example.com/best-cakes-in-australia,对吗?不,这样做不行,因为这将创建新的URL,从SEO的角度来看,维护当前的URL非常重要。 - Abhinav
好的,对我来说它仍然可用...只需在需要显示澳大利亚最佳蛋糕时查找params.products === 781,并从那里推断。 - Kyle Richardson
好的,据我了解(希望我错了!),你好像要打很多字。 - Kyle Richardson
让我们在聊天中继续这个讨论 - Abhinav
显示剩余5条评论
1个回答

2
您可能有一个单独的端点来检查请求的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 />
}

在类似的产品或产品列表组件中,您可以通过 ID 或任何其他键请求特定数据集。
但请记住,如果 SEO 很重要,您很可能希望进行服务器端渲染,这在上面的示例中并没有发生。 `componentDidMount` 仅在浏览器中呈现,您将不得不将其替换为 componentWillMount(React 生命周期中唯一在 SSR 上运行的函数)。
SSR 有点麻烦,特别是对于基于其他请求响应的请求。Redux-saga 可以让这种事情变得更加容易,因此我建议您在这种情况下也采用 saga 的方式。
您可以查看 react-saga-universal 快速了解 saga 和 SSR。

1
根据这个scotch.io的路由参数视频,你可以直接使用this.props.match.params而不需要.location - joeytwiddle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接