react 实现嵌套路由重定向到404页面
- 每次进行react 路由配置的时候都感觉力不从心 , 大脑内存严重不足 , 特在此记录 , 进行一定的说明, 方便日后参考使用
需求: 二级路由结构 , 404页面 ,
- 路由的匹配规则:
route 中的 path 与浏览器 hash 进行匹配 , 只要地址栏的 hash 完整包含 path 的值 , 就会加载对应的 path 的路由
举个栗子 (hash忽略#号)
1 . 当路由的path值为 / 或 * 时 , 任何 hash 下都会加载路由
浏览器hash:/home
----- path值: /
-----当前路由加载
浏览器hash:/home/中兄次之/秩序册Z从
----- path值: /
-----当前路由加载
2 . 地址栏的 hash 完整包含 path 的值 ,
浏览器hash:/home/123
----- path值: /home
-----当前路由加载
浏览器hash:/home/123
----- path值: /home/
-----当前路由加载
浏览器hash:/home
----- path值: /home/
-----当前路由加载
浏览器hash:/123/home
----- path值: /home
-----当前路由不加载
路由结构
- 一级路由
/layout /404
<Switch> //switch作用: 类似于js的switch,只会选取一个匹配项
<Route path="/layout" component={Layout}></Route>
<Route path="/404" component={NotFound}></Route>
<Redirect exact from="/" to="/layout"></Redirect> //优化处理
<Redirect from="*" to="/404" ></Redirect> //最末尾的重定向操作,后面不能插入其他路由
</Switch>
- 二级路由
/layout/home--- /layout/find--- /layout/news--- /layout/profile---
<Switch>
<Route exact path="/layout/home" component={Home}></Route>
<Route exact path="/layout/news" component={News}></Route>
<Route exact path="/layout/findhouse/:id?" component={Findhouse}></Route>
<Route exact path="/layout/profile" component={Profile}></Route>
<Redirect exact path="/layout" to="/layout/home" ></Redirect> //配合一级路由的优化处理,进入到layout直接重定向到home页
<Redirect from="*" to="/404"></Redirect>
</Switch>