安装配置路由
首先使用npm安装模块
npm i react-router-dom -s
在index.js根文件中包裹App组件
BrowserRouter是基于history实现,还有hashrouter,它是通过监测#符号后面的参数实现组件更新的。
import {BrowserRouter} from "react-router-dom";
<BrowserRouter>
<App />
</BrowserRouter>
在需要使用路由的组件中引入路由参数
import { NavLink, Route, Switch,Redirect } from "react-router-dom";
通过设置exact
为true
开启严格匹配,默认为模糊匹配 ,注册子路由时要写上父路由的path
值 ,严格匹配可能会导致二级路由失效,react
路由只能一级一级的匹配下去,switch
的作用是当匹配到路由组件时不用继续往下匹配。
<Switch>
<NavLink activeClassName="btn-success active" to="/home" children="Home" />
<NavLink activeClassName="btn-success active" to="/about" children="About" />
<Route path="/about" component={About}></Route>
<Route path="/home" component={Home}></Route>
<Redirect to="/about"/>
</Switch>
子路由和路由传参
路由传参有三种模式分别是state
,params
,search
。
需要注意子路由是通过父路由继续向下匹配到的,所以在写路由路径的时候需要和父路由前段保持一致。
params传参
<li key={item.id} className="messageli">
<Link to={`/home/firstmessage/${item.id}`}>{item.title}</Link>
</li>
声明接收params参数
<Route path="/home/firstmessage/:id" component={DetailMessage}></Route>
获取params参数
let {id} = this.props.match.params;
search传参
使用search传递参数,需要注意路由一定要比上一级路由多个detail索引,否则在初始时就会渲染报错,使用replace可以直接替换位于history栈顶的历史记录
<Link replace={true} to={`/home/secondmessage/detail/?id=${item.id}&title=${item.title}`}>
{item.title}
</Link>
使用search不需要注册组件时额外接收
<Route path="/home/secondmessage/detail" component={DetailMessage}></Route>
获取search参数
search为后面传递的字符串,引入qs第三方库可以直接将字符串转换为键值对的对象形式。
import qs from 'querystring'
let {search} = this.props.location;
let {id,title}= qs.parse(search.slice(1));
state传参
<li key={item.id} className="messageli">
<Link to = {{pathname:'/home/firstmessage/detail',state:{id:item.id,title:item.titile}}}>
{item.title}
</Link>
</li>
state也不需要声明接收参数
<Route path="/home/firstmessage/detail" component={DetailMessage}></Route>
接收state参数
let {id} = this.props.location.state;
state形式传参参数不会在浏览器的地址栏中显示。