[英]React Router: How to render different components with the same route conditionally
How can I render different components with the same route path with React router but the slug input types are different(int vs string)?如何使用 React 路由器渲染具有相同路由路径的不同组件,但 slug 输入类型不同(int vs string)?
<Switch>
<Route exact path={['/music/:category', '/products/:category']} component={List} />
<Route exact path="/products/:productId" component={Details} />
</Switch
I want to render List component when the path is /products/:category
when the slug is a string.当 slug 是字符串时,我想在路径为
/products/:category
时呈现 List 组件。 I also want to use the same path to render the Details component when its slug, :productId
, is an integer.当它的 slug
:productId
是 integer 时,我还想使用相同的路径来呈现 Details 组件。
I was thinking this might work, but it doesn't.我在想这可能行得通,但事实并非如此。 This renders Details component whether or not the condition.
无论条件与否,这都会呈现详细信息组件。
{pathname.includes('/products') && typeof parseInt(pathname.split('/products/')[1]) === 'number'
? (
<Route exact path="/products/:id" component={Details} />
) : (
<Route exact path={['/music/:slug', '/products/:slug']} component={List} />
)}
Thank you!谢谢!
You can make use of render props of Route to validate the params.您可以使用 Route 的渲染道具来验证参数。
<Route
path="/products/:id"
render={({ match: { params: { id } } }) => {
if(isNaN(id) {
<Route exact path={['/music/:slug', '/products/:slug']} component={List} />
} else {
<Route exact path="/products/:id" component={Details} />
}
}}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.