Multiple path names for a same component in React Router

孤街浪徒 提交于 2019-11-26 08:07:48

问题


I am using the same component for three different routes:

<Router>
    <Route path=\"/home\" component={Home} />
    <Route path=\"/users\" component={Home} />
    <Route path=\"/widgets\" component={Home} />
</Router>

Is there anyway to combine it, to be like:

<Router>
    <Route path=[\"/home\", \"/users\", \"/widgets\"] component={Home} />
</Router>

回答1:


At least with react-router v4 the path can be a regular expression string, so you can do something like this:

<Router>
    <Route path="/(home|users|widgets)/" component={Home} />
</Router>

As you can see it's a bit verbose so if your component/route is simple like this it's probably not worth it.

And of course if this actually comes up often you could always create a wrapping component that takes in an array paths parameter, which does the regex or .map logic reusably.




回答2:


As of react-router v4.4.0-beta.4, and officially in v5.0.0, you can now specify an array of paths which resolve to a component e.g.

<Router>
    <Route path={["/home", "/users", "/widgets"]} component={Home} />
</Router>

Each path in the array is a regular expression string.

The documentation for this approach can be found here.




回答3:


I don't think it is if you use a version of React Router lower than v4.

You can use a map as you would do with any other JSX component though:

<Router>
    {["/home", "/users", "/widgets"].map((path, index) => 
        <Route path={path} component={Home} key={index} />
    )}
</Router>

EDIT

You can also use a regex for the path in react-router v4 as long as it's supported by path-to-regexp. See @Cameron's answer for more info.




回答4:


Other option: use route prefix. /pages for example. You will get

  • /pages/home
  • /pages/users
  • /pages/widgets

And then resolve it in a detailed way inside the Home component.

<Router>
  <Route path="/pages/" component={Home} />
</Router>



回答5:


As per React Router docs the proptype 'path' is of type string .So there is no way you could pass an array as props to the Route Component.

If your intention is to only change route you can use the same component for different route no issues with that




回答6:


As of react-router v4.4 you can just do something like this below.

store the path in a variable and pass down below and use '|' Operator.

let home = "/home" ;
let users = "/users”;
let widgets = "/widgets" ;

<Route path={ {home} | {users} | {widgets} }  component={Home} /> 

so for all path it matches it will render component={Home} which is your need ..



来源:https://stackoverflow.com/questions/40541994/multiple-path-names-for-a-same-component-in-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!