React_16路由配置方法
# 安装依赖
npm i react-router react-router-dom --save
1
# 引入路由组件
import {BrowserRouter as Router,Route,Link,Redirect} from 'react-router-dom'
1
# 编写一个简单路由
在src目录下建立一个AppRouter.js文件,然后写入下面的代码:
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
function Index() {
return <h2>我是首页</h2>;
}
function List() {
return <h2>我是列表页</h2>;
}
function AppRouter() {
return (
<Router>
<ul>
<li> <Link to="/">首页</Link> </li>
<li><Link to="/list/">列表</Link> </li>
</ul>
<Route path="/" exact component={Index} />
<Route path="/list/" component={List} />
</Router>
);
}
export default AppRouter;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
改写src文件目录下的index.js代码:
import React from 'react';
import ReactDOM from 'react-dom'
import AppRouter from './AppRouter'
ReactDOM.render(<AppRouter/>,document.getElementById('root'))
1
2
3
4
5
2
3
4
5
# 路由动态传值
方式一
<Link to="/a/1">首页</Link>
<Route path="/a/:id" exact component={Index} />
import React, { Component } from 'react';
class List extends Component {
constructor(props) {
super(props);
this.state = { }
}
componentDidMount(){
//console.log(this.props.match)
// console.log(this.props.match.params.id)
let tempId=this.props.match.params.id
this.setState({id:tempId })
}
render() {
return ( <h2>List Page</h2> );
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
方式二
<Link to="/a?id=1">首页</Link>
<Route path="/a" exact component={Index} />
import React, { Component } from 'react';
class List extends Component {
constructor(props) {
super(props);
this.state = { }
}
componentDidMount(){
let tempId=this.props.location.query.id
this.setState({id:tempId })
}
render() {
return ( <h2>List Page</h2> );
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 路由重定向
标签式重定向
import { Redirect } from "react-router-dom";
// 引入Redirect后,直接在render函数里使用就可以了
<Redirect to="/home"/>
1
2
3
4
2
3
4
编程式重定向
this.props.history.push("/home");
1
上次更新: 2024/01/30, 00:35:17
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13