在 React Router 中设置相对路径 [英] Setting Relative Path in React Router
问题描述
当路由通过 React Router 中的组件时,有没有办法缩短路径长度?例如,在 App.js
中:
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>
在 Main.js
组件中:
<Switch>
<Route exact path="/main" component={Dashboard} />
<Route exact path="/main/users" component={Users} />
</Switch>
每次我在 Main
组件中时,我可以以某种方式省略在 /main/users
之前添加 /main
吗?可以在该组件中将 /main
设置为 /
还是每次都必须明确键入完整路径?
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?
我看到讨论非常相似(例如:react-router 是否支持相对链接?)但是路由器路径有什么可以配置的吗?<Link to="users"/>
据说可以工作,但我无法获得 <Route path="users"/>
.>
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.
推荐答案
react-router
中没有魔法"会自动注入当前位置,但是你可以很容易地使用this.props.location
从
传递给组件:
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 />
:
因此,如果您已经在 /main
,您可以将路径设置为:
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>
将解析为:
<Switch>
<Route exact path="/main" component={Dashboard} />
<Route exact path="/main/users" component={Users} />
</Switch>
这篇关于在 React Router 中设置相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!