React路由——SPA单页面应用

路由简介

用来控制路径的跳转,一个路由即一组映射关系(key-value键值对形式),key为路径value为方法或者组件

路由分类

前端路由

浏览器路由,value是组件,用来展示页面

后端路由

服务器路由,value是方法,用来处理客户端的请求
router.get(path, function(req, res))

react-router-dom

BrowserRouter与HashRouter

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

Route注册路由:指定path跳转哪个组件
Redirect重定向:当所有路由都无法匹配时,跳转到Redirect指定的路由
Switch单一匹配:提高路由匹配效率

<Switch>
 	<Route path="/home" component={
    
    Home}/>
    <Route path="/about" component={
    
    About}/>
    <Redirect to="/about"/>
</Switch>

Link与NavLink

Link路由链接切换组件,不可以实现路由链接的高亮
NavLink,路由链接切换组件可以实现路由链接的高亮,通过activeClassName指定样式名

<NavLink activeClassName="add" className="list-group-item" to="/home">Home</NavLink>
<NavLink activeClassName="add" className="list-group-item" to="/about">About</NavLink>

路由基本使用

1.明确好界面中的导航区、展示区
2.导航区的a标签改为Link标签
	<Link to="/xxxx">Demo</Link>
3.展示区写Route标签进行路径的匹配
	<Route path='/xxxx’ component={
    
    Demo}/>
4. <App>的最外侧包襄了一个<BrowserRouter><HashRouter>

嵌套路由

1.注册子路由时要写上父路由的path值
​2.路由的匹配是按照注册路由的顺序进行的
 {
    
    /* 注册子路由时要写上父路由的path值 */}
<MyNavLink to="/home/news">News</MyNavLink>
{
    
    /* 注册子路由时要写上父路由的path值 */}
<Route path="/home/news" component={
    
    News}/>

向路由组件传递参数

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
    备注:刷新也可以保留住参数

多种路由跳转方式

push与replace

默认是push
<Link 
     replace
     to={
    
    {
    
    pathname:"/home/message/detail",state:{
    
    id:msgObj.id,title:msgObj.title}>{
    
    msgObj.title}
 </Link>

编程式路由导航

借助this.prosp.history对象上的API对操作路由跳转、前进、后退
this.prosp.history.push()
this.prosp.history.replace()
this.prosp.history.goBack()
this.prosp.history.goForward()
this.prosp.history.go()

withRouter

如果在你想在一般组件使用 路由组件所特有的API 时, 就要借助 withRouter
withRouter可以加工一般组件, 让一般组件具备路由组件所特有的API
withRouter的返回值是一个新组件
export default withRouter(Header)

猜你喜欢

转载自blog.csdn.net/qq_33591873/article/details/128321734
今日推荐