首页 > 解决方案 > 如何在 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/'路线?我真的不喜欢这个网址,太丑了

标签: reactjsreact-routercreate-react-app

解决方案


您需要使用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>

推荐阅读