一:路由组件和普通组件的区别
- 如果说组件是通过路由跳转过来的,我们可以直接获取到history,location,match对象
- 如果说组件是一个普通的组件,那么是不可以直接获取到history,location,match对象的
可以看到我们不可以获取到history和location,match对象
接下来我们使用高阶组件 withRouter
import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Link, Switch,useHistory,withRouter } from 'react-router-dom'
function Teacher(props) {
console.log("props-teacher",props);
return (
<div>
<h1>老师</h1>
</div>
)
}
const WithRouterTeacher = withRouter(Teacher)
function MathTeacher(props) { // 编程式导航跳转
console.log("props-mathTeacher",props);
let history = useHistory();
const jumpHandler = ()=>{
history.push("/teacher")
}
return (
<div>
<h1>数学老师</h1>
<button onClick={jumpHandler}>跳转</button>
<WithRouterTeacher/>
{/* <Teacher></Teacher> */}
</div>
)
}
function EnglishTeacher() {
return (
<div>
<h1>英语老师</h1>
</div>
)
}
export default class index extends Component {
render() {
return (
<div>
<>
<Router>
<ul>
<li><Link to="/teacher">老师</Link></li>
<li><Link to="/teacher/math">数学老师</Link></li>
<li><Link to="/teacher/english">英语老师</Link></li>
</ul>
<Switch>
<Route path="/teacher" exact component={Teacher}></Route>
<Route path="/teacher/math" component={MathTeacher}></Route>
<Route path="/teacher/english" component={EnglishTeacher}></Route>
</Switch>
</Router>
</>
</div>
)
}
}
我们使用高阶组件withRouter,可以看到普通组件也获取了history,location,match对象了
二 路由传参
(1): react-router-dom@5版本
- params动态路由传参 /path/:params
const age = 20;
<li><Link to={`/teacher/${age}`}>老师</Link></li>
<Route path="/teacher/:age" exact component={Teacher}></Route>
获取 this.props.match.params.age
- query传参
history.push({pathname:'/teacher',query: { age: 20 }}) // 编程式导航
获取:this.props.location.query?.age
this.props.history.location.query?.age
这种的缺点就是页面刷新参数会消失掉
- state传参(推荐使用)
history.push({pathname:'/teacher',state: { age: 20 }}) // 编程式导航
获取:this.props.location.state?.age
this.props.history.location.state?.age
4:search结合query-string
yarn add query-string
history.push({pathname:'/teacher',search: "?age=20&name=lxs"}) // 编程式导航
获取:this.props.location.state?.age
let { age,name} = querystring.parse(props.location.search)
let { age,name} = querystring.parse(props.history.location.search)