我正在尝试将我的网站从传统的网络应用程序方法迁移到基于反应的应用程序。在此过程中,我遇到了与网址相关的问题。在我的网站中,在服务器端我使用网址重写将 url 映射到正确的控制器的功能。但我无法弄清楚如何在反应路由器中处理这个事情。我当前的反应路由器代码如下所示
<BrowserRouter>
<Route exact path="/" component={Home}/>
<Route path="/black-forest" component={Product}/>
<Route path="/cakes" component={ProductList}/>
</BrowserRouter>
这段代码是我为构建原型而编写的。但理想情况下有许多不同的网址可以指向ProductList
成分。同样有很多url可以指向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 个这样的 url,它们是使用服务器端创建的UrlRewrite
因此它们不遵循特定的模式。这些网址大多指向ProductList
or Product
成分。
如何在我的 React 路由器配置中为所有这些 url 创建路径?任何指示将不胜感激。
您可能有一个单独的端点来检查请求的网址,该网址返回“Product”或“ProductList”等页面类型,并且根据此结果您可以加载更多数据
例如,假设您有http://www.example.com/api/urlcheck 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 (React 生命周期中唯一在 SSR 上运行的函数)。
SSR 有点麻烦,尤其是基于其他请求的响应的请求。 Redux-saga 让这类东西的生活变得更加轻松,所以我建议在你的情况下也采用 saga 方式。
你可以看一下反应传奇通用 https://github.com/max-gram/react-saga-universal快速启动并运行 saga 和 SSR。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)