reactjs - 如何在 create-react-app 上使用“/”阻止路由
问题描述
我正在创建一个包含四页的简单 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>
一切正常,我的 NavLinks 看起来像这样:
<NavLink exact to='/apartamenty'>
Apartamenty
</NavLink>
我所有的图像都是从公共文件夹加载的。任何其他路线,例如/example
,/przewodnictwo/23
都将我重定向到主页/przewodnictwo
。/przewodnictwo/
但是当我在 url 中写入或者/apartamenty/
这些没有被阻止并且我的图像不是从公共文件夹加载但不存在的时候,就会发生奇怪的事情/public/apartamenty/3.jpg
。
编辑
我忘了在路径图像中添加“/”,现在效果很好。src='1.jpg' 已更改为 src='/1.jpg' 感谢您的帮助。
但是如何阻止'/przewodnictwo/'路线?我真的不喜欢这个网址,太丑了
解决方案
您需要使用strict
关键字来避免斜杠。根据 react-router 文档严格
当 时
true
,带有斜杠的路径只会匹配location.pathname
带有斜杠的 a。当location.pathname
.
<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>
推荐阅读
- image - Visual Studio 中的 DarkImages 文件夹是做什么用的?
- python - 如何在熊猫中使用嵌套字典映射变量?
- c# - ArgumentOutOfRangeException:从字符串中提取字符串
- performance - 我试图通过删除分配来缩短代码,但结果以某种方式完全改变了。有什么解释吗?
- javascript - s3 预签名的 url Javascript 代码不返回完整的 url
- python - 如何查看当前剩余库存
- c# - 如何使用 ProxyKit 添加标头
- java - 如何解决java中的500 Internal Server Error?
- r - 列宽不会针对某些类型的数据自动调整
- php - (Laravel)更改新星资源名称?(仅在界面上)