简体   繁体   English

React Router:如何有条件地渲染具有相同路由的不同组件

[英]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.

相关问题 是否有一种干净的方法来有条件地加载和呈现相同的React Router路由的不同组件? - Is there a clean way to conditionally load and render different components for the same React Router route? 如何在React Router 4/5中有条件地呈现包装组件 - How to conditionally render wrapping components in React Router 4/5 如何使用 React-router 渲染多个组件相同的路由路径 - How to render multiple components same route path with React-router 如何在 React-router-dom 和 React 中动态渲染 Route 组件 - How to dynamically render Route components in React-router-dom and React 如何在 React 中有条件地路由组件? - How to conditionally route components in React? 如何根据redux状态使用相同的反应路由器路由绑定不同的反应组件? - How to Bind different react components with the same react-router route depending on redux state? 无法使用不同的参数渲染相同的路由 react router v4 - Cannot render same route with different parameters react router v4 如何在 React 的初始加载时有条件地渲染不同的组件? - How can I conditionally render different components on initial load in React? React Router不渲染Route组件 - React Router doesn't render Route components React Router:如何使用不同的参数渲染不同的组件 - React Router: How to render different Components with different parameters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM