【问题标题】:Setting Relative Path in React Router在 React Router 中设置相对路径
【发布时间】:2024-04-20 21:25:02
【问题描述】:

当路由通过 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>

Main.js 组件中:

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

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

我看到讨论讨论非常相似的内容(例如:Does react-router support relative links?),但是路由器 paths 有什么可以配置的吗?据说&lt;Link to="users" /&gt; 可以工作,但我无法让&lt;Route path="users" /&gt; 工作。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    react-router 中没有“魔法”会自动注入当前位置,但您可以使用从&lt;Router /&gt; 传递给组件的this.props.location 轻松做到这一点:

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

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

    【讨论】:

    • 除了硬编码'/main/users'之外,是否有任何理由访问当前路径?既然您仍然在主要组件中?
    • @ShaunE.Tobias 访问当前路径而不是硬编码可以更轻松地重用此组件的代码。如果路径是硬编码的并且您更改了应用程序结构,您很可能必须编辑路径。如果它总是拉当前路径,那么您可以重新排列组件而无需更改任何内部结构。
    • 公平点,谢谢!我没有考虑到路径可能会改变。我想在实施过程中你会为这种情况做某种风险评估,因为它可以防止未来的麻烦,但也可能不必要地复杂或昂贵。也许可以通过将路径名放入 const 来清理。再次感谢!
    • 注意:此答案仅适用于BrowserRouter,在使用HashRouter时无效