高階組件——withRouter的原理和用法


作用:

高階組件中的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')  }) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM