问题
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