基于react的hash路由简易实现

基于react的hash路由简易实现

背景介绍

在SPA项目中,若是展现页面繁多,根据前端工程化理论中组件化思想,咱们一般会将不一样的页面,按照功能,职责等进行划分。 这个时候,每一个页面,就须要一个相应的路由去对应。javascript

如今react社区中已经有react-router这个成熟的轮子,咱们能够直接引入并使用。html

但具体hash路由是如何实现的,咱们如今就来探讨一下...前端

在路由设计中,咱们用到了设计模式中的 单例模式 观察者模式 中介者模式java

因此若是有该设计模式基础或实践的小伙伴,会更容易看懂一些...react

开始

首先咱们要了解一下,监听路由改变,实际上是监听2个事件并操做回调,进行渲染:es6

  1. 页面加载事件(window.onload)
  2. 页面url中hash部分改变事件(window.onhashchange)

原生html代码编写

<!doctype html>
<html>
	<head>
		<title>hash-router</title>
	</head>
	<body>
		<ul>
			<li><a href="#/">home</a></li>
			<li><a href="#/login">
					login
					<ul>
						<li><a href="#/login/login1">login1</a></li>
						<li><a href="#/login/login2">login2</a></li>
						<li><a href="#/login/login3">login3</a></li>
					</ul>
				</a></li>
			<li><a href="#/abort">abort</a></li>
		</ul>
		<div id = "content"></div>
	</body>
</html>
复制代码

在这里 咱们指定了一系列路由,包括"#/","#/login"等。而后,咱们就要针对页面onload事件和点击每一个a标签以后hash改变事件来进行处理了。设计模式

原生js代码编写

建立一个HashRouter类

<script type = 'text/javascript'>
	"use strict"
	class HashRouter{
		constructor(){
			this.routers = {},
			this.init();
		}
	}
</script>
复制代码
  1. 在这段代码中 咱们建立了一个HashRouter类,而且指定了一个routers空对象来存储路由信息。
  2. 未来在这个routers对象中,咱们存储路由的名称及回调,如routers = { "#/login" : [ callback1, callback2 ] }。键名为hash路由名称,键值为数组,数组内为跳转到该路由所要执行的回调方法。
  3. 如今,咱们来执行init方法,当HashRouter类被建立的时候,咱们须要执行的一些初始化方法

当HashRouter类被建立时,执行的初始化方法

<script type = 'text/javascript'>
	"use strict"
	class HashRouter{
		constructor(){
			this.routers = {},
			this.init();
		}
		trigger(){
			//取出当前url中的hash部分,并过滤掉参数
			let hash = window.location.hash && window.location.hash.split('?')[0];
			//在routers中,找到相应的hash,并执行已保存在其中的回调方法
			if(this.routers[hash] && this.routers[hash].length > 0){
				for(let i = 0 ; i < this.routers[hash].length ; i++){
					this.routers[hash][i]();
				}	
			}
		}
		init(){
			window.addEventListener('load', () => this.trigger(), false);
			window.addEventListener('hashchange', () => this.trigger(), false);
		}
	}
</script>
复制代码

兼听了页面加载时和hash改变时事件,并针对改变事件作回调处理,即trigger方法前端工程化

须要抛出api,让开发者添加监听事件回调

在上一步咱们进行了初始化,监听了页面hash改变的事件并作相应的处理。可是,咱们须要执行的回调方法,须要开发人员手动添加才行。api

<script type = 'text/javascript'>
	"use strict"
	class HashRouter{
		constructor(){
			this.routers = {},
			this.init();
		}
		listen(path, callback){
			//若是routers中已经存在该hash,则为它pushcallback方法,不然新建一个相应数组,并push回调方法
			if(!this.routers[path]){
				this.routers[path] = [];	
			}
			this.routers[path].push(callback);
		}
		trigger(){
			//取出当前url中的hash部分,并过滤掉参数
			let hash = window.location.hash && window.location.hash.split('?')[0];
			//在routers中,找到相应的hash,并执行已保存在其中的回调方法
			if(this.routers[hash] && this.routers[hash].length > 0){
				for(let i = 0 ; i < this.routers[hash].length ; i++){
					this.routers[hash][i]();
				}	
			}
		}
		init(){
			window.addEventListener('load', () => this.trigger(), false);
			window.addEventListener('hashchange', () => this.trigger(), false);
		}
	}
</script>
复制代码

原生代码实操

<!doctype html>
<html>
	<head>
		<title>hash-router</title>
	</head>
	<body>
		<ul>
			<li><a href="#/">home</a></li>
			<li><a href="#/login">
					login
					<ul>
						<li><a href="#/login/login1">login1</a></li>
						<li><a href="#/login/login2">login2</a></li>
						<li><a href="#/login/login3">login3</a></li>
					</ul>
				</a></li>
			<li><a href="#/abort">abort</a></li>
		</ul>
		<div id = "content"></div>
	</body>
	<script type = 'text/javascript'>
		"use strict"
		let getById = (id) => document.getElementById(id);
	</script>
	<script type = 'text/javascript'>
		"use strict"
		class HashRouter{
			constructor(){
				this.routers = {},
				this.init();
			}
			listen(path, callback){
				//若是routers中已经存在该hash,则为它push回调方法,不然新建一个相应数组,并push回调方法
				if(!this.routers[path]){
					this.routers[path] = [];	
				}
				this.routers[path].push(callback);
			}
			trigger(){
				//取出当前url中的hash部分,并过滤掉参数
				let hash = window.location.hash && window.location.hash.split('?')[0];
				//在routers中,找到相应的hash,并执行已保存在其中的回调方法
				if(this.routers[hash] && this.routers[hash].length > 0){
					for(let i = 0 ; i < this.routers[hash].length ; i++){
						this.routers[hash][i]();
					}	
				}
			}
			init(){
				window.addEventListener('load', () => this.trigger(), false);
				window.addEventListener('hashchange', () => this.trigger(), false);
			}
		}
	</script>
	<script type = 'text/javascript'>
		"use strict"
		let router = new HashRouter();
		router.listen('#/',() => { getById('content').innerHTML = 'home' });
		router.listen('#/login',() => { console.info('login-') });
		router.listen('#/login',() => { console.info('login+') });
		router.listen('#/login',() => { getById('content').innerHTML = 'login' });
		router.listen('#/login/login1',() => { getById('content').innerHTML = 'login1' });
		router.listen('#/login/login2',() => { getById('content').innerHTML = 'login2' });
		router.listen('#/login/login3',() => { getById('content').innerHTML = 'login3' });
		router.listen('#/abort',() => { getById('content').innerHTML = 'abort' });
	</script>
</html>
复制代码

能够看到,在页面点击时,url改变,并执行了咱们根据执行路径所注册的回调方法。此时,一个简易原生的hash-router咱们便实现了数组

对原生代码进行react封装

因为es6模块化横空出世,咱们能够封装存储变量,抛出方法,操做内部变量,不会变量污染。 若是放在之前,咱们须要经过闭包来实现相似功能

实际开发人员须要编写的业务代码部分(文件引用路径根据我的项目不一样能够修改)

import React from 'react';
import ReactDOM from 'react-dom';
import { Router , Route } from './component/router/router';
import MainLayout from './page/main-layout/MainLayout';
import Menu from './page/menu/Menu';
import Login from './page/login/Login';
import Abort from './page/abort/Abort';

const Routers = [
	{ path : '#/login' , menu : 'login' , component : () => Login({ bread : '#/abort' }) },
	{ path : '#/abort' , menu : 'abort' , component : <Abort bread = { '#/login' }/> },
]

export default function RouterPage(){
	return(
		<Router>
			<Menu routers = { Routers }/>
			<MainLayout>
				{ Routers && Routers.map((item, index) => (<Route path = { item.path } key = { index } component = { item.component }/>)) }
			</MainLayout>
		</Router>
	)
}

ReactDOM.render(<RouterPage/>, document.getElementById('easy-router'));
复制代码

下面咱们来逐个分析{ Router , Route , dispatchRouter , listenAll , listenPath }中的每个做用

Router

实际上是个很简单的方法,至关于包装了一层div(未作容错处理,意思一下)

export function Router(props){
	let { className , style , children } = props;
	return(
		<div className = { className } style = { style }>
			{ children }
		</div>
	)
}
Router.defaultProps = {
	className : '',
	style : {},
	children : []
}
复制代码

Route

这个算是路由组件中的核心组件了,咱们须要在Route这个方法中对监听进行封装

这里是业务代码:

//路由组件定义
const Routers = [
	{ path : '#/login' , menu : 'login' , component : () => Login({ bread : '#/abort' }) },
	{ path : '#/abort' , menu : 'abort' , component : <Abort bread = { '#/login' }/> },
]

//return方法中Route的应用
<MainLayout>
	{ Routers && Routers.map((item, index) => (<Route path = { item.path } component = { item.component }/>)) }
</MainLayout>
复制代码

注意,在咱们写Route标签并传参的同时,其实path和component已经注册到变量中保存下来了,当路径条件成立时,就会渲染已经相应存在的component(这里的component能够是ReactDOM或者function,具体参见Routers数组中定义)。话很少说,show me code:

export class Route extends React.Component{
	constructor(props){
		super(props);
		this.state = {
			renderItem : [],            //须要渲染的内容
		}		
	}
	componentDidMount(){
		this.initRouter();
		window.addEventListener('load', () => this.changeReturn());
		window.addEventListener('hashchange', () => this.changeReturn());	
	}
	
	initRouter(){
		let { path , component } = this.props;
		//保证相同的路由只有一个组件 不能重复
		if(routers[path]){
			throw new Error(`router error:${path} has existed`);
		}else{
			routers[path] = component;	
		}
	}
	
	changeReturn(){
		//防止url中有参数干扰监听
		let hash = window.location.hash.split('?')[0];
		let { path } = this.props;
		//当前路由是选中路由时加载当前组件
		if(hash === path && routers[hash]){
			let renderItem;
			//若是组件参数的方法 则执行并push
			//若是组件参数是ReactDOM 则直接渲染
			if(typeof routers[hash] === 'function'){
				renderItem = (routers[hash]())	
			}else{
				renderItem = (routers[hash])		
			}
			//当前路由是选中路由 渲染组件并执行回调
			this.setState({ renderItem }, () => callListen(hash));
		}else{
			//当前路由非选中路由 清空当前组件
			this.setState({ renderItem : [] });
		}		
	}
	
	render(){
		let { renderItem } = this.state;
		return(
		 	<React.Fragment>
				{ renderItem }
			</React.Fragment>
		)
	}
}
复制代码

listenPath和listenAll

这两个方法就是开发者须要添加的监听方法。咱们先来介绍如何使用,经过使用方法,再进行实现。

listenPath('#/login', () => {
	console.info('listenPath login1')
})

listenAll((pathname) => {
	if(pathname === '#/login'){
		console.info('listenAll login')
	}
})
复制代码
  1. listenPath方法,有两个参数,第一个是指定路由,第二个是该路由执行回调
  2. listenAll方法,只有一个方法参数,可是这个方法会将当前hash路径pathname返回,咱们能够根据pathname来进行处理
  3. 这两种方法只是在表现上作了区别,本质仍是同样的
  4. 注意this.setState({ renderItem }, () => callListen(hash)),页面路由为该组件指定path的时候,须要执行回调

具体实现:

/**
 * 路由监听事件对象,分为2部分
 * all array 存listenAll监听方法中注册的数组
 * path array 存listenPath监听方法中注册的hash路径名称和相应的回调方法
 * { all : [callback1, callback2] , path : [{ path: path1, callback : callback1 }, { path : path2, callback : callback2 }] }
 */
let listenEvents = {};	

/**
 * 执行回调
 * 将listenEvents中的all数组中的方法所有执行
 * 遍历listenEvents中的path,找出与当前hash对应的path并执行callback(可能存在多个path相同的状况,由于开发人员能够屡次注册)
 */
function callListen(path){
	if(listenEvents && listenEvents.all && listenEvents.all.length > 0){
		let listenArr = listenEvents.all;
		for(let i = 0 ; i < listenArr.length ; i++){
			listenArr[i](path);
		}	
	}
	if(listenEvents && listenEvents.path && listenEvents.path.length > 0){
		let listenArr = listenEvents.path;
		for(let i = 0 ; i < listenArr.length ; i++){
			if(path === listenArr[i].path){
				listenArr[i].callback();	
			}
		}
	}
}

/**
 * 监听路由并触发回调事件
 * @params
 * path string 须要监听的路由
 * callback function 须要执行的回调
 */
export function listenPath(path, callback){
	if(!listenEvents.path){
		listenEvents.path = [];		
	}		
	listenEvents.path.push({ path, callback });
}

/**
 * 监听路由改变并触发全部回调事件(会将当前路由传出)
 * @params
 * callback function 须要执行的回调
 */
export function listenAll(callback){
	if(!listenEvents.all){
		listenEvents.all = [];	
	}
	listenEvents.all.push(callback);
}
复制代码

dispatchRouter

简单的一个路由跳转方法,没怎么深思,网上应该有更大佬的方法,这里就是意思一下

//路由跳转
export function dispatchRouter({ path = '' , query = {} }){
	let queryStr = [];
	for(let i in query){
		queryStr.push(`${i}=${query[i]}`);
	}
	window.location.href = `${path}?${queryStr.join('&')}`;
}
复制代码

成品展现

Router组件

import React from 'react';

//当前路由组件存储对象{ path : [ component1, component2 ] }
let routers = {};

/**
 * 路由监听事件对象,分为2部分
 * all array 存listenAll监听方法中注册的数组
 * path array 存listenPath监听方法中注册的hash路径名称和相应的回调方法
 * { all : [callback1, callback2] , path : [{ path: path1, callback : callback1 }, { path : path2, callback : callback2 }] }
 */
let listenEvents = {};	

export function Router(props){
	let { className , style , children } = props;
	return(
		<div className = { className } style = { style }>
			{ children }
		</div>
	)
}

Router.defaultProps = {
	className : '',
	style : {},
	children : []
}

/*
 * 执行全部的路由事件
 * @parmas
 * path string 当前的hash路径
 */
function callListen(path){
	if(listenEvents && listenEvents.all && listenEvents.all.length > 0){
		let listenArr = listenEvents.all;
		for(let i = 0 ; i < listenArr.length ; i++){
			listenArr[i](path);
		}	
	}
	if(listenEvents && listenEvents.path && listenEvents.path.length > 0){
		let listenArr = listenEvents.path;
		for(let i = 0 ; i < listenArr.length ; i++){
			if(path === listenArr[i].path){
				listenArr[i].callback();	
			}
		}
	}
}

//路由监听路由并加载相应组件
export class Route extends React.Component{
	constructor(props){
		super(props);
		this.state = {
			renderItem : [],				//须要渲染的内容
		}		
	}
	componentDidMount(){
		this.initRouter();
		window.addEventListener('load', () => this.changeReturn());
		window.addEventListener('hashchange', () => this.changeReturn());	
	}
	
	initRouter(){
		let { path , component } = this.props;
		//保证相同的路由只有一个组件 不能重复
		if(routers[path]){
			throw new Error(`router error:${path} has existed`);
		}else{
			routers[path] = component;	
		}
	}
	
	changeReturn(){
		//防止url中有参数干扰监听
		let hash = window.location.hash.split('?')[0];
		let { path } = this.props;
		//当前路由是选中路由时加载当前组件
		if(hash === path && routers[hash]){
			let renderItem;
			//若是组件参数的方法 则执行并push
			//若是组件参数是ReactDOM 则直接渲染
			if(typeof routers[hash] === 'function'){
				renderItem = (routers[hash]())	
			}else{
				renderItem = (routers[hash])		
			}
			//当前路由是选中路由 渲染组件并执行回调
			this.setState({ renderItem }, () => callListen(hash));
		}else{
			//当前路由非选中路由 清空当前组件
			this.setState({ renderItem : [] });
		}		
	}
	
	render(){
		let { renderItem } = this.state;
		return(
		 	<React.Fragment>
				{ renderItem }
			</React.Fragment>
		)
	}
}

//路由跳转
export function dispatchRouter({ path = '' , query = {} }){
	let queryStr = [];
	for(let i in query){
		queryStr.push(`${i}=${query[i]}`);
	}
	window.location.href = `${path}?${queryStr.join('&')}`;
}

/**
 * 监听路由并触发回调事件
 * @params
 * path string 须要监听的路由
 * callback function 须要执行的回调
 */
export function listenPath(path, callback){
	if(!listenEvents.path){
		listenEvents.path = [];		
	}		
	listenEvents.path.push({ path, callback });
}

/**
 * 监听路由改变并触发全部回调事件(会将当前路由传出)
 * @params
 * callback function 须要执行的回调
 */
export function listenAll(callback){
	if(!listenEvents.all){
		listenEvents.all = [];	
	}
	listenEvents.all.push(callback);
}
复制代码

业务代码

代码结构

这里简单写了个结构

index.html

<!doctype html>
<html>
	<head>
		<title>简易路由</title>	
	</head>
	<body>
		<div id = 'easy-router'></div>
	</body>
</html>
复制代码

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router , Route } from './component/router/router';
import MainLayout from './page/main-layout/MainLayout';
import Menu from './page/menu/Menu';
import Login from './page/login/Login';
import Abort from './page/abort/Abort';

const Routers = [
	{ path : '#/login' , menu : 'login' , component : () => Login({ bread : '#/abort' }) },
	{ path : '#/abort' , menu : 'abort' , component : <Abort bread = { '#/login' }/> },
]

export default function RouterPage(){
    return(
		<Router>
			<Menu routers = { Routers }/>
			<MainLayout>
				{ Routers && Routers.map((item, index) => (<Route path = { item.path } component = { item.component }/>)) }
			</MainLayout>
		</Router>
	)
}

ReactDOM.render(<RouterPage/>, document.getElementById('easy-router'));
复制代码

MainLayout.js

import React from 'react';

export default function MainLayout({ children }){
	return(
		<div>
			{ children }
		</div>
	)
}
复制代码

Menu.js

import React from 'react';

export default function Menu({ routers }){
	return(
		<div>
			{ routers && routers.map((item, index) => {
				let { path , menu , component } = item;
				return(
					<div key = { path } onClick = {() => { window.location.href = path }}><a>{ menu }</a></div>
				)
			}) }
		</div>
	)
}
复制代码

Login.js

import React from 'react';
import { listenAll , listenPath } from '../../component/router/router';

listenPath('#/login', () => {
	console.info('listenPath login1')
})

listenAll((pathname) => {
	if(pathname === '#/login'){
		console.info('listenAll login')
	}
})

export default function Login(props = {}){
	let { bread } = props;
	return (
		<div style = {{ width : '100%' , height : '100%' , border : '1px solid #5d9cec' }}>
			<div>login</div>
			{ bread && <a href = { bread }>bread{ bread }</a> }
		</div>
	)
}
复制代码

Abort.js

import React from 'react';
import { listenAll , listenPath } from '../../component/router/router';

listenPath('#/abort', () => {
	console.info('listenPath abort')
})

listenAll((pathname) => {
	if(pathname === '#/abort'){
		console.info('listenAll abort')
	}
})

export default function Abort(props = {}){
	let { bread } = props;
	return (
		<div style = {{ width : '100%' , height : '100%' , border : '1px solid #5d9cec' }}>
			<div>abort</div>
			{ bread && <a href = { bread }>bread{ bread }</a> }
		</div>
	)
}
复制代码

大功告成!

相关文章
相关标签/搜索