当前位置: 首页 > news >正文

react学习——23react中的路由的使用(重要)

一、路由的基本使用

		1.明确好界面中的导航区、展示区2.导航区的a标签改为Link标签<Link to="/xxxxx">Demo</Link>3.展示区写Route标签进行路径的匹配<Route path='/xxxx' component={Demo}/>4.<App>的最外侧包裹了一个<BrowserRouter><HashRouter>
 <Link className="list-group-item" to="/about">About</Link><Link className="list-group-item" to="/home">Home</Link>
{/*  注册路由组件--->  */}
<Route path={'/about'} component={About}></Route>
<Route path={'/home'} component={Home}></Route>
 <BrowserRouter><App />
</BrowserRouter>

二、路由组件与一般组件

1.写法不同:一般组件:<Demo/>路由组件:<Route path="/demo" component={Demo}/>2.存放位置不同:一般组件:components路由组件:pages3.接收到的props不同:一般组件:写组件标签时传递了什么,就能收到什么路由组件:接收到三个固定的属性history:go: ƒ go(n)goBack: ƒ goBack()goForward: ƒ goForward()push: ƒ push(path, state)replace: ƒ replace(path, state)location:pathname: "/about"search: ""state: undefinedmatch:params: {}path: "/about"url: "/about"

三、NavLink与封装NavLink

1.NavLink可以实现路由链接的高亮,通过activeClassName指定样式名

封装

import React, {Component} from "react";
import {NavLink} from "react-router-dom";export default class MyNavLink extends Component {render(){const {title} = this.props;return(<NavLink activeClassName='atguigu' className="list-group-item" {...this.props}/>);}
}

使用

<MyNavLink to="/about" title="About" a={1} b={2} c={3}>About</MyNavLink><MyNavLink to="/home" title="Home">Home</MyNavLink>

四、Switch的使用

		1.通常情况下,path和component是一一对应的关系。2.Switch可以提高路由匹配效率(单一匹配)。
<Switch><Route path={'/about'} component={About}></Route><Route path={'/home'} component={Home}></Route><Route path={'/home'} component={Test}></Route>
</Switch>

五、解决多级路径刷新页面样式丢失的问题

1.public/index.html 中 引入样式时不写 ./ 写 / (常用)
2.public/index.html 中 引入样式时不写 ./ 写 %PUBLIC_URL% (常用)
3.使用HashRouter

六、路由的严格匹配与模糊匹配

1.默认使用的是模糊匹配(简单记:【输入的路径】必须包含要【匹配的路径】,且顺序要一致)
2.开启严格匹配:<Route exact={true} path="/about" component={About}/>
3.严格匹配不要随便开启,需要再开,有些时候开启会导致无法继续匹配二级路由

七、Redirect的使用

1.一般写在所有路由注册的最下方,当所有路由都无法匹配时,跳转到Redirect指定的路由
2.具体编码:<Switch><Route path="/about" component={About}/><Route path="/home" component={Home}/><Redirect to="/about"/></Switch>

八、嵌套路由

1.注册子路由时要写上父路由的path值
2.路由的匹配是按照注册路由的顺序进行的

父路由

<MyNavLink to="/about">About</MyNavLink>
<MyNavLink to="/home">Home</MyNavLink>
{/* 注册路由 */}
<Switch><Route  path="/about" component={About}/><Route  path="/home" component={Home}/><Redirect to="/home"/>
</Switch>

子路由

<li>{/*<MyNavLink to="/home/news">News</MyNavLink>*/}<MyNavLink to="/home/news">news</MyNavLink>
</li>
<li><MyNavLink to="/home/message">Message</MyNavLink>
</li>
</ul>
{/* 注册路由 */}
<Switch>
<Route path={'/home/news'} component={News}></Route><Route path={'/home/message'} component={Message}></Route><Redirect to={'/home/news'}></Redirect>
</Switch>

九、向路由组件传递参数

1.params参数路由链接(携带参数)<Link to='/demo/test/tom/18'}>详情</Link>注册路由(声明接收)<Route path="/demo/test/:name/:age" component={Test}/>接收参数:this.props.match.params
2.search参数路由链接(携带参数)<Link to='/demo/test?name=tom&age=18'}>详情</Link>注册路由(无需声明,正常注册即可)<Route path="/demo/test" component={Test}/>接收参数:this.props.location.search备注:获取到的search是urlencoded编码字符串,需要借助querystring解析
3.state参数路由链接(携带参数)<Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>注册路由(无需声明,正常注册即可)<Route path="/demo/test" component={Test}/>接收参数:this.props.location.state备注:刷新也可以保留住参数
import React, { Component } from 'react'
import {Link,Route} from "react-router-dom";
import Detail from "./Detail";export default class Message extends Component {state = {messageArr:[{id:1,title:'001'},{id:2,title:'002'},{id:3,title:'003'}]}render() {const {messageArr} = this.statereturn (<div><ul>{messageArr.map(item=>{return <li key={item.id}>{/*向路由组件传递params参数*/}{/*<Link to={`/home/message/detail/${item.id}/${item.title}`}>{item.title}</Link>&nbsp;&nbsp;*/}{/*向路由组件传递search参数*/}{/*<Link to={`/home/message/detail/?id=${item.id}&title=${item.title}`}>{item.title}</Link>*/}{/*向路由组件传递state参数*/}<Link to={{pathname:'/home/message/detail',state:{id:item.id,title:item.title}}}>{item.title}</Link>&nbsp;&nbsp;</li>})}</ul><hr/>{/*声明接收params参数*/}{/*<Route path="/home/message/detail/:id/:title" component={Detail}/>*/}{/*search参数无需声明接收,正常接收路由即可*/}{/*<Route path={"/home/message/detail"} component={Detail}/>*/}{/*state参数无需声明接收,正常接收路由即可*/}<Route path={"/home/message/detail"} component={Detail}/></div>)}
}
import React, {Component} from "react";
// import qs from 'qs'
const DetailData=[{id:1,content:'content1'},{id:2,content:'content2'},{id:3,content:'content3'}
]
export default class Detail extends Component {render(){console.log(this.props);//接收params参数// const {id,title}=this.props.match.params;//接收search参数// const {search}=this.props.location// const {id,title}=qs.parse(search.slice(1))//接收state参数const {id,title}=this.props.location.state;const findResult=DetailData.find(item=>item.id===Number(id));return(<ul><li>ID:{id}</li><li>Title:{title}</li><li>Content:{findResult.content}</li></ul>);}
}

十、编程式路由导航

				借助this.prosp.history对象上的API对操作路由跳转、前进、后退-this.prosp.history.push()-this.prosp.history.replace()-this.prosp.history.goBack()-this.prosp.history.goForward()-this.prosp.history.go()
replaceShow = (id,title)=>{console.log(id,title)//replace跳转+携带params参数// this.props.history.replace(`/home/message/detail/${id}/${title}`)//replace跳转+携带search参数// this.props.history.replace(`/home/message/detail?id=${id}&title=${title}`)//replace跳转+携带state参数this.props.history.replace(`/home/message/detail?`,{id,title})}pushShow(id, title) {//push跳转+携带params参数// this.props.history.push(`/home/message/detail/${id}/${title}`)//push跳转+携带search参数//this.props.history.push(`/home/message/detail?id=${id}&title=${title}`)//push跳转+携带state参数this.props.history.push(`/home/message/detail?`,{id,title})}goback=()=> {this.props.history.goBack()}goforward=() =>{this.props.history.goForward()}goTest = () => {this.props.history.go(2)}

十一、BrowserRouter与HashRouter的区别

	1.底层原理不一样:BrowserRouter使用的是H5的history API,不兼容IE9及以下版本。HashRouter使用的是URL的哈希值。2.path表现形式不一样BrowserRouter的路径中没有#,例如:localhost:3000/demo/testHashRouter的路径包含#,例如:localhost:3000/#/demo/test3.刷新后对路由state参数的影响(1).BrowserRouter没有任何影响,因为state保存在history对象中。(2).HashRouter刷新后会导致路由state参数的丢失!!!4.备注:HashRouter可以用于解决一些路径错误相关的问题。

相关文章:

  • 大气热力学(6)——位温和假相当位温
  • Linux 防火墙配置指南:firewalld不同服务管理的应用案例(十个)
  • Java-方法
  • 插8张显卡的服务器有哪些?
  • 基于Unity3D的Rokid AR Glass项目开发环境搭建
  • bug - while parsing file included at
  • LeetCode—和为K的子数组(前缀和)
  • 在SpringBoot使用AOP防止接口重复提交
  • C# Bitmap类型与Byte[]类型相互转化详解与示例
  • 需求分析|泳道图 ProcessOn教学
  • Games101——光珊化——深度缓存——shading着色 1
  • 旷野之间3 – CTO 应具备的技能
  • 【ARMv8/v9 GIC 系列 5.1 -- GIC GICD_CTRL Enable 1 of N Wakeup Function】
  • 记一次mysql导出到达梦数据库
  • 8.5结构体嵌套结构体
  • 【技术性】Search知识
  • C++类中的特殊成员函数
  • HashMap ConcurrentHashMap
  • Intervention/image 图片处理扩展包的安装和使用
  • Java小白进阶笔记(3)-初级面向对象
  • jQuery(一)
  • MaxCompute访问TableStore(OTS) 数据
  • node.js
  • PyCharm搭建GO开发环境(GO语言学习第1课)
  • TypeScript实现数据结构(一)栈,队列,链表
  • Vultr 教程目录
  • Webpack4 学习笔记 - 01:webpack的安装和简单配置
  • Xmanager 远程桌面 CentOS 7
  • 百度地图API标注+时间轴组件
  • 闭包--闭包作用之保存(一)
  • 关于使用markdown的方法(引自CSDN教程)
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 基于Javascript, Springboot的管理系统报表查询页面代码设计
  • 力扣(LeetCode)22
  • 使用agvtool更改app version/build
  • 王永庆:技术创新改变教育未来
  • gunicorn工作原理
  • hi-nginx-1.3.4编译安装
  • 树莓派用上kodexplorer也能玩成私有网盘
  • ​DB-Engines 12月数据库排名: PostgreSQL有望获得「2020年度数据库」荣誉?
  • #LLM入门|Prompt#2.3_对查询任务进行分类|意图分析_Classification
  • #NOIP 2014# day.1 T3 飞扬的小鸟 bird
  • #我与Java虚拟机的故事#连载03:面试过的百度,滴滴,快手都问了这些问题
  • $LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
  • (6)添加vue-cookie
  • (超详细)2-YOLOV5改进-添加SimAM注意力机制
  • (第30天)二叉树阶段总结
  • (附源码)python房屋租赁管理系统 毕业设计 745613
  • (附源码)计算机毕业设计大学生兼职系统
  • (剑指Offer)面试题41:和为s的连续正数序列
  • (六)Flink 窗口计算
  • (论文阅读32/100)Flowing convnets for human pose estimation in videos
  • (算法)Travel Information Center
  • (心得)获取一个数二进制序列中所有的偶数位和奇数位, 分别输出二进制序列。
  • (一)、python程序--模拟电脑鼠走迷宫