第六章 react-router4
理解
react-router
-
react的一个插件库
-
专门用来实现一个SPA应用
-
基于react的项目基本都会用到此库
SPA
-
单页Web应用(single page web application,SPA)
-
整个应用只有一个完整的页面
-
点击页面中的链接不会刷新页面, 本身也不会向服务器发请求
-
当点击路由链接时, 只会做页面的局部更新
-
数据都需要通过ajax请求获取, 并在前端异步展现
路由
什么是路由
-
一个路由就是一个映射关系(key:value)
-
key为路由路径, value可能是
function/component
路由分类
-
后台路由: node服务器端路由, value是function, 用来处理客户端提交的请求并返回一个响应数据
-
前台路由: 浏览器端路由, value是component, 当请求的是路由path时, 浏览器端前没有发送http请求, 但界面会更新显示对应的组件
后台路由
-
注册路由:
router.get(path, function(req, res))
-
当node接收到一个请求时, 根据请求路径找到匹配的路由, 调用路由中的函数来处理请求, 返回响应数据
前端路由
- 注册路由:
<Route path="/about" component={About}>
- 当浏览器的hash变为#about时, 当前路由组件就会变为About组件
前端路由实现
-
history库
-
网址: https://github.com/ReactTraining/history
-
管理浏览器会话历史(history)的工具库
-
包装的是原生BOM中window.history和window.location.hash
-
-
history API
History.createBrowserHistory()
: 得到封装window.history的管理对象History.createHashHistory()
: 得到封装window.location.hash的管理对象history.push()
: 添加一个新的历史记录history.replace()
: 用一个新的历史记录替换当前的记录history.goBack()
: 回退到上一个历史记录history.goForword()
: 前进到下一个历史记录history.listen(function(location){})
: 监视历史记录的变化
react-router相关API
组件
<BrowserRouter>
<HashRouter>
<Route>
<Redirect>
<Link>
<NavLink>
<Switch>
其他
history对象
match对象
withRouter函数
基本路由使用
-
下载react-router:
npm install --save react-router@4
-
引入bootstrap.css:
<link rel="stylesheet" href="/css/bootstrap.css">