Router之React-Router

//页面路由

js
1
2
window.location.href='url';
history.back();

//hash路由

js
1
2
3
4
window.location='#hash'
window.onhashchange=function(){
console.log(window.location.hash);
}

//H5路由

js
1
2
3
4
5
6
7
8
9
10
11
//推进一个状态
history.pushState('name','title','/path');
//替换一个状态
history.replaceState('name','title','/path');
//popstate
window.onpopstate=function (ev) {
console.log(window.location.href)
console.log(window.location.pathname)
console.log(window.location.hash)
console.log(window.location.search)
}

React-Router

<BrowserRouter>/<HashRouter>,路由方式

<Route>,路由规则

<Switch>,路由选项

<Link>/<NavLink>,跳转导航

<Redirect>,自动跳转

js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//哈希路由地址显示localhost:8000#/a
import {HashRouter as Router,Route, link} from 'react-route-dom'
//Browser路由地址显示localhost:8000/a
import {BrowserRouter as Router,Route, link,Switch} from 'react-route-dom'

class A extents React.Component{
constructor(props){
super(props)
}
render(){
return (
<\div>
Component A
<\Switch>
//exact完全匹配
<\Route exact
path={`${this.props.match.path}/:id`}
render={(route)=>{
return <\div>不带参数<\/div>
}
}}/>
<\Route
path={`${this.props.match.path}/:id`}
render={(route)=>{
return <\div>参数:{route.match.params.id}<\/div>
}
}}/>

<\/Switch>
<\/div>
)
}
}

class B extents React.Component{
constructor(props){
super(props)
}
render(){
return <\div>Component B<\/div>
}
}

class Wrapper extents React.Component{
constructor(props){
super(props)
}
render(){
return (
<\div>
<\Link to="/a">组件A<\/link>
<\Link to="/a">组件B<\/link>
{this.props.children}
<\/div>
)
}
}

ReactDOM.render(
<\Wrapper>
<\Route path='/a/:id' component={A}>组件A<\/Route>
<\Route path='/b' component={B}>组件B<\/Route>
<\/Wrapper>,
document.getElementById('app')
)