高阶组件——withRouter的原理和用法

2023-06-25,,

作用:

高阶组件中的withRouter, 作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.

把不是通过路由切换过来的组件中,将react-router 的 history、location、match 三个对象传入props对象上

1. 默认情况下必须是经过路由匹配渲染的组件才存在this.props,才拥有路由参数,才能使用编程式导航的写法,执行this.props.history.push('/ ')跳转到对应路由的页面
然而不是所有组件都直接与路由相连(通过路由跳转到此组件)的,当这些组件需要路由参数时,使用withRouter就可以给此组件传入路由参数,此时就可以使用this.props
2. 高阶组件中的withRouter, 作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.此时这个组件就具备了路由的属性
 
使用withRouter:
比如app.js这个组件,一般是首页,不是通过路由跳转过来的,而是直接从浏览器中输入地址打开的,如果不使用withRouter此组件的this.props为空,没法执行props中的history、location、match等方法

 1 import { Switch, Route, Redirect, withRouter } from "react-router-dom";
2
3 import Home from "./components/Home.jsx";
4 import User from "./components/User.jsx";
5
6 class App extends React.Component {
7 constructor(props) {
8 super(props)
9 console.log(props) // 此时props里就具备了路由对象

      props.history.listen((e) => {           // 只要是具备路由功能的组件都可以使用这个方法,参数接收一个回调函数
           console.log(e, '路由参数的变化')
         })

10   }
11 render() {
12 return (
13 <div>
14 <Switch>
15 <Redirect from="/" to="/home" exact />
16 <Route exact path="/home" component={Home}></Route>
17 <Route exact path="/user" component={User}></Route>
18 </Switch>
19 </div>
20 );
21 }
22 }
23
24 export default withRouter(App); //参数是一个组件,返回一个组件

 
props.history.listen()
只要是具备路由功能的组件都可以使用这个方法,参数接收一个回调函数,但是是有切换页面时才会触发这个方法,很像vue中的组件内的钩子,当路由变化的时候做一些事情

props.history.listen((e) => {  console.log(e, '开启了withRouter')  })

高阶组件——withRouter的原理和用法的相关教程结束。

《高阶组件——withRouter的原理和用法.doc》

下载本文的Word格式文档,以方便收藏与打印。