在 React Router 中设置相对路径

Sch*_*ppi 5 reactjs react-router

当路由通过 React Router 中的组件时,有没有办法缩短路径长度?例如,在App.js:

<Switch>
  <Route exact path="/" component={Landing} />
  <Route exact path="/login" component={Login} />
  <PrivateRoute path="/main" component={Main} />
  <Route component={NotFound} />
</Switch>
Run Code Online (Sandbox Code Playgroud)

在Main.js组件中:

<Switch>
    <Route exact path="/main" component={Dashboard} />
    <Route exact path="/main/users" component={Users} />
</Switch>
Run Code Online (Sandbox Code Playgroud)

我可以/main在/main/users每次进入Main组件之前以某种方式省略添加吗?可以/main设置/在该组件内还是每次都必须明确键入完整路径?

我看到讨论非常相似的东西(例如:react-router 支持相对链接吗?)但是路由器路径有什么可以配置的吗?<Link to="users" />据说可以工作,但我无法到达<Route path="users" />。

Cha*_*nda 6

没有“魔法”react-router会自动注入当前位置,但是您可以使用this.props.location从<Router />以下位置传递给组件的方法轻松完成:

因此,如果您已经在/main,则可以将路径设置为:

<Switch>
  <Route exact path={`${this.props.location.pathname}`} component={Dashboard} />
  <Route exact path={`${this.props.location.pathname}/users`} component={Users} />
</Switch>
Run Code Online (Sandbox Code Playgroud)

这将解决为:

<Switch>
  <Route exact path="/main" component={Dashboard} />
  <Route exact path="/main/users" component={Users} />
</Switch>
Run Code Online (Sandbox Code Playgroud)