Router原理和React-Router

本文深入探讨了浏览器Router的工作原理,包括其历史、跳转和事件三个核心要素,以及常见的页面Router、HashRouter和H5Router。同时,详细介绍了React-Router的使用方法,包括BrowserRouter、HashRouter、Switch、Link等组件的实战应用。
摘要由CSDN通过智能技术生成

Router原理和React-Router

1 Rouer原理

Router指的是浏览器中一种处理访问先后关系的机制,简单点来说就是允许我们在不同页面进行跳转然后记录跳转关系还能原路退回的机制。

三个要素:

  • 历史:栈的形式
  • 跳转:负责不同页面的挑战动作,并且可传递参数
  • 事件:打开新页面或退回上一页面触发的逻辑

2 常见Router

  • 页面Router
  • Hash Router
  • H5 Router

代码演示

// 页面路由
window.location.href = 'http://www.baidu.com';
// 回退
history.back();

// hash 路由
window.location.href = '#test';
// 监听hash路由
window.onhashchange = function(){
	console.log('current hash:',window.location.hash);
};

// h5 路由
// 推进一个状态
history.pushState('test','Title','#test');
// 替换一个状态
history.replaceState('test',null,'/index/test')
// 监听h5 后退
window.onpopstate = function(e){
	console.log('h5 router change:',e.state);
	console.log(window.location.href);
	console.log(window.location.pathname);
	console.log(window.location.hash);
	console.log(window.location.search);
}

3 React-Router

  • React官方提供的路由插件,单页路由必备
  • 使用版本:react-router-dom@v4.2.2
  • 动态路由(静态路由:在一个根节点下定义所有路由;动态路由:路由放在组件里,须需要时再去定义),纯react组件

3.1 常见

  • <BrowserRouter> / <HashRouter>,路由方式
  • <Router>,路由规则
  • <Switch>,路由选项
  • <Link/> / <NavLink>,跳转导航
  • <Redirect>,自动跳转

3.2 代码演示

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route, Link, Switch} from 'react-router-dom'

class A extends React.Component{
	constructor(props){
		super(props);

	}
	render(){
		return(
			<div>
				Component A
				<Switch>
					{/* 完全匹配 */}
					<Route exact path={`${this.props.match.path}`} render={(route) =>{
							return <div>当前组件是不带参数的A</div>
						}}/>
					<Route path={`${this.props.match.path}/sub`} render={(route) =>{
							return <div>当前组件是Sub</div>
						}}/>
					<Route path={`${this.props.match.path}/:id`} render={(route) =>{
							return <div>当前组件是带参数的A,参数是:{route.match.params.id}</div>
						}}/>
				</Switch>
			</div>
		);
	}
}

class B extends React.Component{
	constructor(props){
		super(props);

	}
	render(){
		return(
			<div>Component B</div>
		);
	}
}

class Wrapper extends React.Component{
	constructor(props){
		super(props);

	}
	render(){
		return(
			<div>
				<Link to="/a">组件A</Link>
				<br/>
				<Link to="/a/123">带参数的组件A</Link>
				<br/>
				<Link to="/b">组件B</Link>
				<br/>
				<Link to="/a/sub">/a/sub</Link>
				{this.props.children}
			</div>
		);
	}
}

ReactDOM.render(
	<Router>
		<Wrapper>
			<Route path="/a" component={A}/>
			<Route path="/b" component={B}/>
		</Wrapper>
	</Router>
	,
	document.getElementById('app')
);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值