作用:把不是通過路由切換過來的組件中念恍,將react-router 的 history、location掀宋、match 三個對象傳入props對象上雳刺,
例如react app.js這個組件一般是首頁,不是通過路由跳轉過來的划址,而是直接從瀏覽器中輸入地址打開的扔嵌,如果不使用withRouter此組件的this.props為空,沒法執(zhí)行props中的history夺颤、location痢缎、match等方法。
設置withRouter很簡單只需要兩步:(1)import?{withRouter}?from?"react-router-dom";(2)將App組件 withRouter(app) 一下
設置完打印就可以看見history世澜,location独旷,match等屬性了
介紹一個簡單應用
可以根據路由切換瀏覽器的title屬性,對props.history進行監(jiān)聽寥裂,切換路由的時候獲取當前的路由路徑嵌洼,同時可以根據不同的路由設置不同的瀏覽器title標題
import React,{Component} from 'react'import {Switch,Route,NavLink,Redirect,withRouter} from 'react-router-dom'import One from './One'import NotFound from './NotFound'class App extends Component{
? ? ? ? constructor(props){
? ? ? ? ? ? ? ? super(props);
? ? ? ? ? ? ? ? props.history.listen((location)=>{//在這里監(jiān)聽location對象console.log(location.pathname);//切換路由的時候輸出"/one/users"和"/one/companies"switch(location.pathname){//根據路徑不同切換不同的瀏覽器titlecase'/one/users' : document.title = '用戶列表';break;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? case'/one/companies' : document.title = '公司列表';break;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? default:break;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? })
? ? ? ? }
? ? ? ? render(){
? ? ? ? ? ? ? ? return(
? ? ? ? ? ? ? ? ? ? ? ? 用戶列表? ? ? ? ? ? ? ? ? ? ? ? 公司列表? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
)? ? ? ? }
}
export defaultwithRouter(App);
當然還有眾多用途,如果你使用了編程式導航的寫法:
this.props.history.push('/detail') 去跳轉頁面封恰,但是報 this.props.history 錯誤 undefined咱台,請在此組件中使用?withRouter 將 history 傳入到 props上。