react-router教程


准备工作

yarn add react-router-dom

入口文件:src/index.js
1
2
3
4
5
import React from 'react';
import ReactDOM from 'react-dom'
import AppRouter from './AppRouter'

ReactDOM.render(<AppRouter/>,document.getElementById('root'))
路由文件:src/AppRouter.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
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Index from './Pages/Index'
import List from './Pages/List'

function AppRouter() {
return (
<Router>
<ul>
<li> <Link to="/">首页</Link> </li> // <Link to='/'> 相当于点击事件跳转
<li><Link to="/list/">列表</Link> </li>
</ul>
<Route path="/" exact component={Index} /> // exact: 精准匹配,不然/list也会展示Index的组件
<Route path="/list/" component={List} /> // 相应路径显示的内容
<Route path="/dynamicRoute/:id" exact component={List} /> // 动态路由
</Router>
);
}

export default AppRouter;


// ./Pages/Index.js
import React, { Component } from 'react';
class Index extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
return ( <h2>JSPang.com</h2> );
}
}
export default Index;

// ./Pages/List.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom'

class List extends Component {
constructor(props) {
super(props);
this.state = { list: [
{ id: 123, title: '我是123' },
{ id: 234, title: '我是234' },
{ id: 345, title: '我是345' }
] }
}
render() {
return (
<ul>
{ this.state.list.map(item =>
<li key={item.id}><Link to={`/dynamicRoute/${item.id}`}>{item.title}</Link></li>) // 动态路由
}
</ul>
);
}
componentDidMount () {
console.log(this.props.match)
}
}
export default Index;
获取路由信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ./Pages/List.js
import React, { Component } from 'react';
class Index extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
return ( <h2>ListPage.com</h2> );
}
componentDidMount(){
console.log(this.props.match) // { path: "/dynamicRoute/:id", url: '/dynamicRoute/123', params: {id: "123"} }
}
}
export default Index;
路由重定向
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// ./Pages/Index.js
import React, { Component } from 'react';

class Index extends Component {
constructor(props) {
super(props);
this.state = { }
this.props.history.push('/list')
}
render() {
return ( <h2>JSPang.com</h2> );
}
componentDidMount () {
console.log(this.props.match)
}
}

export default Index;