【问题标题】:How to remove trailing / on root route with react-router如何使用 react-router 删除根路由上的尾随 /
【发布时间】:2019-08-23 00:08:45
【问题描述】:

我有几条路线:

 www.example.com/rootRoute/flags
 www.example.com/rootRoute/test
 www.example.com/rootRoute/derp

对于路线主页,我希望我的路线是:

 www.example.com/rootRoute

但是 react-router 在最后强制使用 / 所以我的根路由是:

 www.example.com/rootRoute/

知道如何解决这个问题吗?

 "react-router": "^4.3.1",
 "react-router-dom": "^4.3.1",

我已经在我的交换机中设置了路径并路由到所需的路径,但地址栏中始终附加一个 /。

 <Switch>
  <Route path={'/rootRoute/flags'} component={FeatureFlagsPage} />
  <Route path={'/rootRoute/test'} component={DerpComponent} />
  <Route path={'/rootRoute'} component={TestComponent} />

我希望根路由的末尾没有 /。

【问题讨论】:

  • 你能显示你的组件链接在哪里吗?
  • 链接没关系,整个应用程序都有链接组件,重要的是/rootRoute添加了一个example.com/rootRoute/,我想摆脱尾部斜杠,我是可以通过在 window.history 上调用 replaceState 来做到这一点
  • 嗯,你的意思是当你导航时你的应用程序会自动获取/自动?看来原始演示没有这个问题reacttraining.com/react-router/web/example/route-config。我也没有经历过
  • 是的,nw5y4q47pj.codesandbox.io 注意到末尾的 / 了吗?再次检查您的链接。
  • 不,我没有。也许你有一些可能受影响的插件。可以试试隐身模式吗?

标签: reactjs react-router-v4


【解决方案1】:

一些小改动:

/rootRoute 移至顶部并精确添加。去掉花括号...

<Switch>
  <Route exact path='/rootRoute' component={TestComponent} />
  <Route path='/rootRoute/flags' component={FeatureFlagsPage} />
  <Route path='/rootRoute/test' component={DerpComponent} />
</Switch>

【讨论】:

  • 它会删除尾随的 / 吗?
  • 是的,这通常是正确的做法......@Rami
  • 另外,如果它是根路由,为什么不简单地将其设为根路由,就像&lt;Route exact path='/' component={TestComponent} /&gt; 一样,其余的可以是&lt;Route path='/flags' component={FeatureFlagsPage} /&gt; 等等...
  • 你错过了我认为的问题。我们有 example.com/rootRoute/everyotherroute。现在对于主页组件,我希望路由是 www.example.com/rootRoute 但目前它是 example.com/rootRoute/
  • 无论如何...上面的解决方案应该可以解决您遇到的问题...这是文档的链接 - 很棒的文档:reacttraining.com/react-router/web/guides/quick-start
【解决方案2】:

我最终使用了 history.replaceState('', 'State Title', 'Root Path');

在我的索引组件中。

【讨论】:

    【解决方案3】:

    您可以向路由器添加基本名称,如下所示:

    <Router basename='/rootRoute'>
      <Switch>
        <Route exact path='/' component={ TestComponent }/>
        <Route path='/flags' component={ FeatureFlagsPage }/>
        <Route path='/test' component={ DerpComponent }/>
      </Switch>
    </Router>
    

    【讨论】:

      【解决方案4】:

      我可以通过添加 来消除 URL 中的斜杠:

        <Switch>
      
          // put this rule before your Routes
          <Redirect from="/:url*(/+)" to={window.location.pathname.slice(0, -1)} />
      
          // and your Routes go here...
      
        </Switch>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-05
        • 2018-11-19
        • 2017-05-04
        • 2023-04-11
        • 2016-04-13
        • 2018-06-04
        • 2020-07-14
        • 2020-07-02
        相关资源
        最近更新 更多