本文已参与「新人创作礼」活动,一起开启掘金创作之路
第一节:单页面(SPA)的理解
· 整个页面只有一个完整的页面
· 当页面中链接点击时不会跳转,只会局部刷新
·数据的请求都是通过ajax请求,进行异步展现。
第二节:路由的基本使用
2.1 定义
定义:一个路由就是 路径(/about)对应的组件(About);
2.2 react-router-dom的使用
定义:react的插件库,基于react项目都会用到此库。
安装:npm add react-router-dom@5
2.3 路由组件
路由组件:把路由组件放入”pages”文件夹,普通组件放入”component”文件。
2.1 编写路由
引入路由:import {xxx} from 'react-router-dom',此组件使用分别导出,需要引入谁就引入谁。
· link: 编写路由组件链接
关于我们
· BrowserRouter(history API):路由链接和注册路由都写在此内。
·Route:注册路由****
path是对用的路径,component对应的组件
备注:BrowserRouter可以放在最外层 index.js内,包裹整个APP组件。****
2.2 NavLink 用法
Link升级版,加上NavLink点中会加一个Active样式。
关于我们
activeClassName:指定要加的样式名称,默认为:active。 houver
2.3 NavLink 封装
创建一般组件:MyNavLink,代码如下:
import React, { Component } from 'react'
import {NavLink} from 'react-router-dom'
export default class MyNavLink extends Component {
render() {
const {to} = this.props;
return (
<NavLink className='nav' to={to}>{this.props.children}</NavLink )
}
}
注:标签体内容可以通过props.children接收,所以简写方式:
<NavLink className='nav' {...this.props}/>
组件使用: <MyNavLink to="/about">关于我们
2.4 Switch
找到了组件就不会往下继续找
<Switch>
<Route path="/about" component={About}/>
<Route path="/about" component={About2}/>
<Redirect to="/404"/>
</Switch>
2.8路由组件和一般组件的区别
1:写法不同 。
2:存放位置不同。
3:普通组件不传props就收不到,但路由组件可以收到三个重要的值:history,location,match。
2.9 路由匹配
navlink to="/home/a/b"
2.10 Redirect
当没有路由匹配,重定向。
模糊匹配:
精准匹配:
,尽量不开启,需要的时候在开。
路由错乱
第三节:路由高级使用
3.1 嵌套路由
3.2 params传递参数
·携带参数
<Link to={/about/fzlc/content/${item.id}/${item.title}
}>{item.title}
·声明接收参数
<Route path="/about/fzlc/content/:id/:title" component={Content}/>
·得到参数
Const {params} = this.props.match;
3.3 传递search参数
·携带参数
{item.title}·无需声明接收
·得到参数
this.props.location.search 接收的结果为:?id=001&title=ttt
·安装:npm add query-string
const {id,title} = qs.parse(search.slice(1));
3.4 传递state参数
·携带参数****
<Link to={{pathname:'/about/news/show/',state:{id:item.id,title:item.title}}}>{item.title}
·无需声明接收
·得到参数
const {id,title} = this.props.location.state;//地址栏不显示参数。
3.5 push和replace模式
Replace 是替换不留下痕迹
<Link replace to={/about/fzlc/content/?id=001&title=ttt
}>{item.title}
3.6 编程式路由
// push跳转
pushshow = (id,title)=>{
// param传参
// this.props.history.push(/about/fzlc/content/${id}/${title}
);
//search传参
// this.props.history.push(/about/fzlc/content/?id=${id}&title=${title}
);
// state传参
this.props.history.push(/about/fzlc/content/
,{id,title});
}
//replace跳转
this.props.history.replace(/about/fzlc/content/${id}/${title}
);
3.6 获得路由路径
Location pathname
Match path 、url
3.7 withRoute用法
让普通组件拥有路由组件的history,也能实现前进,后退等方法。
this.props.history.goBack() //返回
this.props.history.goForward()//前进
this.props.history.go(-2)
import {withRouter} from 'react-router-dom'
export default withRouter(Header)