react路由介绍
在react中有两种路由模式,分别是 hash 和 history ,为了方便大家理解,我们先来了解下这两个路由
两者区别
外观
使用hash模式下的URL,网络路径中会有一个#号进行拼接,而history没有带 #
兼容性
hash能够兼容到IE8,history只能够兼容到IE10
运行原理
hash是通过window.onhashchange的方式进行监听变化,从而实现无刷新跳转,每次hash变化都会触发网页跳转,也就是浏览器的前进和后退,虽然hash会改变URL,但是不会触发页面重新加载。简而言之所有页面的跳转都是在客户端进行的,跳转的过程不算是一次http请求,所以这种模式对SEO优化是很不友好的。
history模式在对当前页面进行刷新时,此时浏览器会重新发起请求。history是利用H5的 history中新增的两个API pushState() 和 replaceState() 和一个事件onpopstate来监听URL变化,history每次刷新都会重新请求服务器,需要服务端来允许地址是否可访问,如果没有设置的话,会导致404页面。
如果对项目没有特殊要求,可以直接使用hash模式开发,如果需要SEO优化那么一定要选history
react路由使用
了解了hash和history基础介绍之后,我们接着引入react项目下token失效之后怎么跳转到登录页面
hash模式路由跳转处理
首先路由模块是引入HashRouter==> hash模式的
import { HashRouter as Router, Route, Switch, Redirect } from 'react-router-dom';import Login from '@/pages/login';import BlogMenu from '@/pages/layout';import Register from '@/pages/register';import NotFound from '@/pages/404';<Router><Switch><Route path="/api/login" component={Login}></Route><Route path="/api/register" component={Register}></Route><Routepath="/"render={() =>localStorage.getItem('token') ? (<BlogMenu />) : (<Redirect to="/api/login"></Redirect>)}></Route><Route path="*" component={NotFound}></Route></Switch></Router>
在utils -> http.js 请求文件中进行验证的处理
case 401:// tokenconsole.log('服务器认证失败');localStorage.removeItem('token');// 退出登录window.location.href = '#/api/login';break;
使用原生的window方法,强制跳转到 login 页面,这种方式在hash模式下没有问题,在history下跳转时会出现白屏的情况
history模式路由跳转处理
在 utils 文件夹中新建一个history.js文件,引入history并导出
import { createBrowserHistory } from 'history';export default createBrowserHistory();
将hash模式路由进行修改,找到路由文件,将 HashRouter as Router修改为Router,然后引入history文件,在标签<Router>中引入history
import { Router, Route, Switch, Redirect } from 'react-router-dom';import Login from '@/pages/login';import BlogMenu from '@/pages/layout';import Register from '@/pages/register';import NotFound from '@/pages/404';import history from '@/utils/history';<Router history={history}><Switch><Route path="/api/login" component={Login}></Route><Route path="/api/register" component={Register}></Route><Routepath="/"render={() =>localStorage.getItem('token') ? (<BlogMenu />) : (<Redirect to="/api/login"></Redirect>)}></Route><Route path="*" component={NotFound}></Route></Switch></Router>
在 utils -> http.js 请求文件中引入history文件,进行路由的跳转
import history from './history';history.push('/api/login')
参考链接:
react 中token失效Router路由跳回login页面的(history出现白屏)解决方案
hash和history的区别
