一、路由学习
1.路由的由来
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-q5fBDi8Q-1649343572989)(img/路由的由来.png)]
2.路由的阶段
2.1后端路由阶段
-
早期的网站开发整个HTML页面是由服务器来渲染的.
- 服务器直接生产渲染好对应的HTML页面, 返回给客户端进行展示.
-
但是, 一个网站, 这么多页面服务器如何处理呢?
-
一个页面有自己对应的网址, 也就是URL.
-
URL会发送到服务器, 服务器会通过正则对该URL进行匹配, 并且最后交给一个Controller进行处理.
-
Controller进行各种处理, 最终生成HTML或者数据, 返回给前端.
-
这就完成了一个IO操作.
-
-
上面的这种操作, 就是后端路由.
- 当我们页面中需要请求不同的路径内容时, 交给服务器来进行处理, 服务器渲染好整个页面, 并且将页面返回给客户顿.
- 这种情况下渲染好的页面, 不需要单独加载任何的js和css, 可以直接交给浏览器展示, 这样也有利于SEO的优化.
-
后端路由的缺点:
- 一种情况是整个页面的模块由后端人员来编写和维护的.
- 另一种情况是前端开发人员如果要开发页面, 需要通过PHP和Java等语言来编写页面代码.
- 而且通常情况下HTML代码和数据以及对应的逻辑会混在一起, 编写和维护都是非常糟糕的事情.
2.2前后端分离阶段
-
前端渲染的理解:
- 每次请求涉及到的静态资源都会从静态资源服务器获取;
- 这些资源包括HTML+CSS+JS,然后在前端对这些请求回来的资源进行渲染;
- 需要注意的是,客户端的每一次请求,都会从静态资源服务器请求文件;
- 同时可以看到,和之前的后端路由不同,这时后端只是负责提供API了;
-
前后端分离阶段:
-
随着Ajax的出现, 有了前后端分离的开发模式;
-
后端只提供API来返回数据,前端通过Ajax获取数据,并且可以通过JavaScript将数据渲染到页面中;
-
这样做最大的优点就是前后端责任的清晰,后端专注于数据上,前端专注于交互和可视化上;
-
并且当移动端(iOS/Android)出现后,后端不需要进行任何处理,依然使用之前的一套API即可;
-
目前很多的网站依然采用这种模式开发(jQuery开发模式);
2.3单页面富应用(SPA)
-
单页面富应用的理解:
- 单页面富应用的英文是single-page application,简称SPA;
- 整个Web应用只有实际上只有一个页面,当URL发生改变时,并不会从服务器请求新的静态资源;
- 而是通过JavaScript监听URL的改变,并且根据URL的不同去渲染新的页面;
-
如何可以应用URL和渲染的页面呢?前端路由
- 前端路由维护着URL和渲染页面的映射关系;
- 路由可以根据不同的URL,最终让我们的框架(比如Vue、React、Angular)去渲染不同的组件;
- 最终我们在页面上看到的实际就是渲染的一个个组件页面;
3.前端路由的原理
-
前端路由是如何做到URL和内容进行映射呢?监听URL的改变。
-
URL发生变化,同时不引起页面的刷新有两个办法:
- 通过URL的hash改变URL;
- 通过HTML5中的history模式修改URL;
-
当监听到URL发生变化时,我们可以通过自己判断当前的URL,决定到底渲染什么样的内容。
3.1、URL的hash
<script>
const routerViewEl = document.querySelector('.router-view')
// 不会引起页面的刷新
window.addEventListener('hashchange', () => {
switch (location.hash) {
case '#/home':
return routerViewEl.innerHTML = '<h2>HOME</h2>'
case '#/about':
return routerViewEl.innerHTML = '<h2>ABOUT</h2>'
default:
return routerViewEl.innerHTML = '<h2>default</h2>'
}
})
</script>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-J1hXJe4u-1649343572991)(img/URL的hash.png)]
3.2HTML5的history
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<a href="/home">home</a>
<a href="/about">about</a>
<div class="router-view">default</div>
</div>
<script>
const routerViewEl = document.querySelector('.router-view')
const aEls = document.querySelectorAll('a')
for (let el of aEls) {
el.addEventListener('click', e => {
e.preventDefault();
const href = el.getAttribute('href');
// console.log(href);
history.pushState({}, "", href);
console.log(location);
historyChange()
})
}
// 执行返回操作的时候,依然来到historyChange()
window.addEventListener('popstate', historyChange)
// 监听不到go操作,只能监听state改变操作
window.addEventListener('go', historyChange)
function historyChange() {
switch (location.pathname) {
case '/home':
return routerViewEl.innerHTML = '<h2>HOME</h2>'
case '/about':
return routerViewEl.innerHTML = '<h2>ABOUT</h2>'
default:
return routerViewEl.innerHTML = '<h2>default</h2>'
}
}
</script>
</body>
</html>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9Q7JFrL6-1649343572992)(img/html5的history.png)]
4.react-router的基本使用
4.1安装
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Kq4jPkhK-1649343572993)(img/react-router.png)]
4.2Router的基本使用
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LvmRAdwn-1649343572993)(img/router的基本使用.png)]
4.3NavLink的使用
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uwrHq660-1649343572994)(img/NavLink.png)]
4.4Switch的作用
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hIRhvPb8-1649343572995)(img/switch的作用.png)]
4.5Redirect–重定向
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ycn9nAkv-1649343572996)(img/重定向.png)]
4.6嵌套路由
4.7手动路由跳转
如果要实现手动路由跳转,必须要让app包裹在withRouter这个高阶函数里面,这个函数是由react-router-dom提供的
import React, { PureComponent } from 'react'
import Home from './pages/home'
import About from './pages/about'
import Profile from './pages/profile'
import NoMatch from './pages/noMatch'
import Productions from './pages/production'
import {
NavLink,
Route,
Switch,
withRouter
} from 'react-router-dom'
class App extends PureComponent {
constructor(props) {
super(props)
this.state = {
links: [
{to: '/home', title: '首页'},
{to: '/about', title: '关于'},
{to: '/profile', title: '我的'}
]
}
}
render() {
return (
<div>
{
this.state.links.map((item, index) => {
return <NavLink key={index} to={item.to}>{item.title}</NavLink>
})
}
<button onClick={() => this.goPro()}>production</button>
<Switch>
<Route exact path='/home' component={Home}/>
<Route path="/about" component={About}/>
<Route path="/profile" component={Profile}/>
<Route path="/productions" component={Productions}/>
<Route component={NoMatch}/>
</Switch>
</div>
)
}
// 此时不可以使用history
goPro() {
this.props.history.push('/productions')
}
}
export default withRouter(App)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KfjzpXky-1649343572996)(img/手动路由跳转.png)]
4.8参数传递
params在match中获取
pathname在location中获取
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BfYKKL3T-1649343572997)(img/有关路由的三个参数.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UAMBabYP-1649343572998)(img/参数传递.png)]
4.9react-router-config
4.9.1在router/index.js中编写routes,配置路由映射的关系数组
import Home from '../pages/home'
import About from '../pages/about'
import Profile from '../pages/profile'
import NoMatch from '../pages/noMatch'
import Productions from '../pages/production'
import Detail from '../pages/detail'
import Detail2 from '../pages/detail2'
const routes = [
{ path: '/home', component: Home, exact: true },
{ path: '/about', component: About },
{ path: '/profile', component: Profile },
{ path: '/productions', component: Productions },
{ path: '/detail:id', component: Detail },
{ path: '/detail2', component: Detail2 },
{ component: NoMatch },
]
export default routes
4.9.2在app.js中使用renderRoutes函数完成配置
4.9.3在涉及嵌套的时候,需要在子组件中也用renderRoute(routes)占位,那如何拿到routes呢?如果该子组件也是由renderRoute渲染的,那么可以通过this.props.route拿到相关的路由配置
import React, { PureComponent } from 'react'
import routes from './router'
import { renderRoutes} from 'react-router-config'
import {
NavLink,
withRouter
} from 'react-router-dom'
class App extends PureComponent {
constructor(props) {
super(props)
this.state = {
links: [
{to: '/home', title: '首页'},
{to: '/about', title: '关于'},
{to: '/profile', title: '我的'}
]
}
}
render() {
const id = 123
const info = {name: 'why', age: 18, height: 1.88}
return (
<div>
{
this.state.links.map((item, index) => {
return <NavLink key={index} to={item.to}>{item.title}</NavLink>
})
}
<button onClick={() => this.goPro()}>production</button>
<NavLink to={`/detail/${id}`}>详情</NavLink>
<NavLink to={{
pathname: '/detail2/123',
search: '?name=coderwhy',
query: {name: 'why', age: 18, height: 1.88},
state: info
}}>详情2</NavLink>
{/* <Switch>
<Route exact path='/home' component={Home}/>
<Route path="/about" component={About}/>
<Route path="/profile" component={Profile}/>
<Route path="/detail/:id" component={Detail}/>
<Route path="/detail2" component={Detail2}/>
<Route path="/productions" component={Productions}/>
<Route component={NoMatch}/>
</Switch> */}
{renderRoutes(routes)}
</div>
)
}
// 此时不可以使用history
goPro() {
this.props.history.push('/productions')
}
}
export default withRouter(App)