代码:
import React from 'react';
import {
BrowserRouter as Router,
Route,
Link,
useParams
} from 'react-router-dom'
export default function MyRouter() {
return (
<Router>
<ul>
<li><Link to="/">首页</Link></li>
<li><Link to="/about">关于</Link></li>
<li><Link to="/user/张三">用户</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}></Route>
<Route path="/about" component={About}></Route>
<Route path="/user/:id" component={User}></Route>
</Router>
)
}
function Home() {
return (
<h2>我是首页</h2>
)
}
function About() {
return (
<h2>我是关于</h2>
)
}
class User extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
//在此处查看props的内容
componentDidMount() {
console.log(this.props);
let tempId = this.props.match.params.id
this.setState({id: tempId})
}
render() {
return (
<h2>我是</h2>
)
}
}
props中的数据:
- history
- location
- match
history对象
history保存着用户上网的历史纪录
- length属性: 保存着历史记录的数量;
- go方法: 可以在用户的历史纪录中任意跳转;
- back方法: 移动到上一个网址;
-
forward方法: 移动到下一个网址;
location对象:
location对象提供了与当前窗口中加载的文档有关的信息
- hash: URL中的hash值
- host:服务器名称和端口号
- hostname: 不带端口号的服务器名称
- pathname: 返回URL中的目录和(或)文件名
- port: 返回端口号
- protocol: 返回协议名
-
search: 返回URL的查询字符串
match对象:
URL和Route匹配时,Route创建match作为props中的一个属性传递给被渲染的组件;
match对象的属性:
- params:params是从匹配的URL中解析出的path中的参数
- isExact: 布尔值,完全匹配时为true,反之为false
- path: Route的path属性,构建嵌套路由时会使用
-
url: URL的匹配部分