如何为多个路由渲染一个组件?

How to render a component for multiple routes?

我有一个组件,我想用 URL 参数为多条路线渲染。我正在使用 react-router v4。现在我正在使用三种不同的路线。

<Route
    path="/"
    render={path => (
        <Component
          path={path}
        /> 
    )}
/>
<Route
    path="/a/:urlParams1"
    render={path => (
        <Component
          path={path}
        /> 
    )}
/>
<Route
    path="/a/:urlParams1/b/:urlParams2"
    render={path => (
        <Component
          path={path}
        /> 
    )}
/>
有没有更好的方法来使用 URL 参数为多个路由渲染组件?我尝试使用正则表达式作为路径,但我无法访问参数。

您目前无法将路径数组作为路径发送,但是有一个针对此 here 的开放功能请求。

我现在可以通过这种方法为您的问题建议一个更简洁的版本:

const componentRoutes = [
  {
    path: "/"
  },
  {
    path: "/a/:urlParams1"
  },
  {
    path: "/a/:urlParams1/b/:urlParams2"
  }
]


<Switch>
  {
    componentRoutes.map(route => (
      <Route key={route.path} exact 
             path={route.path} 
             render={path => (<Component path={path}/>)}/>
    ))
   }
</Switch>

您可以移除Switch组件,仅供示例。