如何在create-react-app上使用'/'阻止路由

时间:2019-06-27 07:54:52

标签: reactjs react-router 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的主页。但是,当我在URL /przewodnictwo//apartamenty/中写入内容时,发生了奇怪的事情,它们没有被阻止,并且不是从公用文件夹而是从/public/apartamenty/3.jpg加载了我的图像。 >

编辑

我忘了在路径图像上添加'/',现在可以正常使用了。 src ='1.jpg'已更改为src ='/ 1.jpg'谢谢您的帮助。

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

2 个答案:

答案 0 :(得分:1)

您需要使用strict关键字来避免出现斜杠。根据反应路由器文档的严格要求

  

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>

答案 1 :(得分:1)

要阻止尾部斜杠与您的路线匹配,可以在Route组件上使用strict道具。

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

  

<Route>

     

严格:笨蛋

     

为true时,带有斜杠的路径将仅与location.pathname带有斜杠的匹配。当location.pathname中还有其他URL段时,这无效。

     

enter image description here