Setting Relative Path in React Router

佐手、 提交于 2020-05-27 12:22:10

问题


Is there a way to shorten the path length when routes are passed through components in React Router? For example, in App.js:

<Switch>
  <Route exact path="/" component={Landing} />
  <Route exact path="/login" component={Login} />
  <PrivateRoute path="/main" component={Main} />
  <Route component={NotFound} />
</Switch>

And in Main.js component:

<Switch>
    <Route exact path="/main" component={Dashboard} />
    <Route exact path="/main/users" component={Users} />
</Switch>

Can I somehow omit adding /main before /main/users everytime I am in the Main component? Can /main be set to / within that component or do I have to explicitly type the full path every time?

I see discussions talking about something very similar (for example: Does react-router support relative links?) but is there anything for Router paths that can be configured? <Link to="users" /> is said to work but I can't get <Route path="users" /> to.


回答1:


There is no "magic" in react-router that will automatically inject the current location, but you can do it pretty easily using this.props.location that is passed to the component from <Router />:

So if you are already at /main, you could set your paths to:

<Switch>
  <Route exact path={`${this.props.location.pathname}`} component={Dashboard} />
  <Route exact path={`${this.props.location.pathname}/users`} component={Users} />
</Switch>

Which would resolve as:

<Switch>
  <Route exact path="/main" component={Dashboard} />
  <Route exact path="/main/users" component={Users} />
</Switch>


来源:https://stackoverflow.com/questions/53711964/setting-relative-path-in-react-router

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