Router原理和React-Router

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Solitarily/article/details/85873260

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官方提供的路由插件,单页路由必备
  • 使用版本:[email protected]
  • 动态路由(静态路由:在一个根节点下定义所有路由;动态路由:路由放在组件里,须需要时再去定义),纯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')
);

猜你喜欢

转载自blog.csdn.net/Solitarily/article/details/85873260