【问题标题】:How to block routes with '/' on create-react-app如何在 create-react-app 上使用“/”阻止路由
【发布时间】:2019-11-09 04:55:39
【问题描述】:

我正在创建一个包含四个页面的简单 SPA,但我发现了一个导致我的应用程序崩溃的大问题。我有四个路线:

<Switch>
     <Route exact path='/przewodnictwo' component={Conductivity} />
     <Route exact path='/apartamenty' component={Apartments} />
     <Route exact path='/przewoz_osob' component={Transport} />
     <Route exact path='/narciarstwo' component={Skiing} />
     <Redirect from='*' to='/przewodnictwo' />
</Switch>

一切正常,我的导航链接看起来像这样:

<NavLink exact to='/apartamenty'>
       Apartamenty
</NavLink>

我所有的图片都是从公共文件夹加载的。像/example/przewodnictwo/23 这样的任何其他路由都将我重定向到/przewodnictwo 的主页。但是当我在 url /przewodnictwo//apartamenty/ 中写入时发生了奇怪的事情,这些都没有被阻止,并且我的图像不是从公共文件夹而是从不存在的 /public/apartamenty/3.jpg 加载的。

编辑

我忘记在路径图像中添加“/”,现在可以完美运行。 src='1.jpg' 已更改为 src='/1.jpg' 感谢您的帮助。

但是如何阻止 '/przewodnictwo/' 路由?我真的不喜欢这个网址,太丑了

【问题讨论】:

  • 你能显示代码,你显示/加载图片的位置吗?
  • 你用的是哪个路由器?
  • @cbdev420 import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom'; v^4.3.1
  • @BorysKupar 是的,我忘记了,我已将 / 添加到路径中并且效果很好,但仍然如何阻止此 url: '/przewodnictwo/' ??
  • 您的意思是,如果有人输入/przewodnictwo/,您希望找不到结果?

标签: reactjs react-router create-react-app


【解决方案1】:

要阻止尾部斜杠匹配您的路由,您可以在 Route 组件上使用 strict 属性。

来源:https://reacttraining.com/react-router/web/api/Route/strict-bool

&lt;Route&gt;

严格:布尔

当为 true 时,带有斜杠的路径只会匹配带有斜杠的 location.pathname。当 location.pathname 中有额外的 URL 段时,这不起作用。

【讨论】:

  • 非常感谢你是第一个所以我接受了你的回答
【解决方案2】:

您需要使用strict 关键字来避免斜杠。根据严格的 react-router 文档

true 时,带有斜杠的路径只会匹配 location.pathname 带有斜杠。这在有时没有效果 是 location.pathname 中的附加 URL 段。

<Switch>
     <Route exact strict path='/przewodnictwo' component={Conductivity} />
     <Route exact strict path='/apartamenty' component={Apartments} />
     <Route exact strict path='/przewoz_osob' component={Transport} />
     <Route exact strict path='/narciarstwo' component={Skiing} />
     <Redirect from='*' to='/przewodnictwo' />
</Switch>

【讨论】:

    猜你喜欢
    • 2018-08-21
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2017-02-08
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多