1. 为什么使用react-router
当需要页面切换而又不想重新加载新页面的时候,就需要用到路由。同时还可以增强组织资源的语义,每个页面的业务功能都是高内聚,低耦合的,通过?url?就可以将页面进行很好的隔离。
2. react-router的基本原理
一句话:实现URL与UI界面的同步。
其中在react-router中,URL 对应 Location?对象,而UI是由 react? component 来决定的,这样就转变成?location 与?components 之间的同步问题。
注:传统服务端路由一旦定义好了,就是一个配置文件,是静态的放在那里,但是对于?React Router?来说它是动态路由,因为只有当页面?render?的时候,路由才会被解析。
3.组件层面描述实现过程
在react-router 中最主要的component 是Router ?RouterContext ?Link ,history 库起到了中间桥梁的作用。
4.?关键API
<Link> 普通连接,不会触发浏览器刷新,页面变化是通过?React - Router?来控制的。
<NavLink> 类似 Link 但是会添加当前选中状态(蓝色的链接状态)。
<Prompt> 满足条件时提示用户是否离开当前页面。
<Redirect> 重定向当前页面,例如登录判断。
<Route> 路由配置的核心标记,路由匹配时显示对应组件(且只要路由匹配,组件都会显示)
<Switch> 只显示第一个匹配的路由。
5. react-router 使用下的优点:
6.?动态路由的简单使用
1)导入路由库
import { ? ? MemoryRouter as Router, ? ? NavLink, ? ? Redirect, ? ? Switch, ? ? Route } from 'react-router-dom';
2)路由路径,子组件的也需要都现在根路由的地方
< Router>
? ? ? <Switch>? ????????????<Route exact path="/" ?????????????????? render={() => (<Redirect to="/EarlyWarnQuery" />)} ? //重定向到首页面 ?????????????/>
????????????<Route path={'/EarlyWarnQuery'} component={(EarlyWarnQuery)} /> ????????????<Route path={'/Fretail'} ?component={FileQuery} /> ??????</Switch>? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? </ Router>
3)哪里需要链接,写哪里
<NavLink key={item.id} to={{ pathname:`/cardDetail/${item.id}`, state: item? }}> ?????????<span onClick={this.cardShow} >张三三</span> ? </NavLink>
//? ?`/cardDetail/${item.id}`?带参路由? ? ? ? ?state: item? 是传给子组件的参? ??
4)子组件接受传参,赋值给当前组件的 state
function CardDetail(props) { ? ? let info = props.location.state ? props.location.state : props.getCardInfo;
}
注意:
?? 1.?重定向
????????react-router4的文档用的是BrowserRouter,BroswerRouter是需要服务端配合的,服务端重定向到首页
?????2. 最外层路由只能有一个子元素? ? ?
< Router>
<div>
? <Switch>
? ? <Route exact path="/"
? ? ? ? ? render={() => (<Redirect to="/EarlyWarnQuery" />)} //重定向到首页面
? ? ? />
? ? <Route path={'/EarlyWarnQuery'} component={connect(mapStateToProps)(EarlyWarnQuery)} />
? ? ? ? ? ? ? ? ? ? ? ? ? ??
? ? <Route path={'/Fretail'} ?component={FileQuery} />
</Switch>
? ?</div>? ? ? ? ? ? ? ? ? ? ? ??
</ Router>
参考资料:
https://blog.csdn.net/tangzhl/article/details/79696055
https://blog.csdn.net/EcbJS/article/details/106670514?spm=1001.2014.3001.5501
https://www.cnblogs.com/erduyang/p/6757788.html
|