react-router4 介绍

react-router 的理解:

1) react 的一个插件库
2) 专门用来实现一个 SPA 应用
3) 基于 react 的项目基本都会用到此库

SPA  的理解:

1) 单页 Web 应用(single page web application,SPA)
2) 整个应用只有一个完整的页面
3) 点击页面中的链接不会刷新页面, 本身也不会向服务器发请求
4) 当点击路由链接时, 只会做页面的局部更新
5) 数据都需要通过 ajax 请求获取, 并在前端异步展现

  路由的理解:

1) 什么是路由?
  a. 一个路由就是一个映射关系(key:value)
  b. key 为路由路径, value 可能是 function/component
2) 路由分类
  a. 后台路由: node 服务器端路由, value 是 function, 用来处理客户端提交的请求并返
回一个响应数据

  b. 前台路由: 浏览器端路由, value 是 component, 当请求的是路由 path 时, 浏览器端前没有发送 http 请求, 但界面会更新显示对应的组件

3) 后台路由
  a. 注册路由: router.get(path, function(req, res))
  b. 当 node 接收到一个请求时, 根据请求路径找到匹配的路由, 调用路由中的函数来
处理请求, 返回响应数据
4) 前端路由
  a. 注册路由: <Route path="/about" component={About}>
  b. 当浏览器的 hash 变为#about 时, 当前路由组件就会变为 About 组件

前端路由的实现

1) history 库
  a. 网址: https://github.com/ReactTraining/history
  b. 管理浏览器会话历史(history)的工具库
  c. 包装的是原生 BOM 中 window.history 和 window.location.hash
2) history API
  a. History.createBrowserHistory(): 得到封装 window.history 的管理对象
  b. History.createHashHistory(): 得到封装 window.location.hash 的管理对象
  c. history.push(): 添加一个新的历史记录
  d. history.replace(): 用一个新的历史记录替换当前的记录
  e. history.goBack(): 回退到上一个历史记录
  f. history.goForword(): 前进到下一个历史记录
  g. history.listen(function(location){}): 监视历史记录的变化

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>history test</title>
</head>
<body>
<p><input type="text"></p>
<a href="/test1" onclick="return push('/test1')">test1</a><br><br>
<button onClick="push('/test2')">push test2</button><br><br>
<button onClick="back()">回退</button><br><br>
<button onClick="forword()">前进</button><br><br>
<button onClick="replace('/test3')">replace test3</button><br><br>
<script type="text/javascript"
src="https://cdn.bootcss.com/history/4.7.2/history.js"></script>
<script type="text/javascript">
let history = History.createBrowserHistory() // 方式一
// history = History.createHashHistory() // 方式二
// console.log(history)
function push (to) {
history.push(to)
return false
}
function back() {
history.goBack()
}
function forword() {
history.goForward()
}
function replace (to) {
history.replace(to)
}
history.listen((location) => {
console.log(' 请求路由路径变化了', location)
})
原文地址:https://www.cnblogs.com/jnba/p/12633901.html