1. 程式人生 > >withRouter的作用和一個簡單應用

withRouter的作用和一個簡單應用

通過 必須 情況下 style route 瀏覽器中 type red 用途

作用:把不是通過路由切換過來的組件中,將react-router 的 history、location、match 三個對象傳入props對象上 默認情況下必須是經過路由匹配渲染的組件才存在this.props,才擁有路由參數,才能使用編程式導航的寫法,執行this.props.history.push(‘/detail‘)跳轉到對應路由的頁面 然而不是所有組件都直接與路由相連(通過路由跳轉到此組件)的,當這些組件需要路由參數時,使用withRouter就可以給此組件傳入路由參數,此時就可以使用this.props 一:如何使用withRouter: 比如app.js這個組件,一般是首頁,不是通過路由跳轉過來的,而是直接從瀏覽器中輸入地址打開的,如果不使用withRouter此組件的this.props為空,沒法執行props中的history、location、match等方法。 我就通過在App.js組件中使用withRouter來簡單介紹一下: 設置withRouter很簡單只需要兩步:(1)引入 (2)將App組件 withRouter() 一下
import React,{Component} from ‘react‘
import {Switch,Route,NavLink,Redirect,withRouter} from 
‘react-router-dom‘ //引入withRouter import One from ‘./One‘ import NotFound from ‘./NotFound‘ class App extends Component{ //此時才能獲取this.props,包含(history, match, location)三個對象 console.log(this.props); //輸出{match: {…}, location: {…}, history: {…}, 等} render(){return (<div className=‘app‘> <NavLink to=‘/one/users‘>用戶列表</NavLink> <NavLink to=‘/one/companies‘>公司列表</NavLink> <Switch> <Route path=‘/one/:type?‘ component={One} /> <Redirect from=‘/‘ to=‘/one‘ exact /> <Route component={NotFound} /> </Switch> </div>) } } export
default withRouter(App); //這裏要執行一下WithRouter

二:介紹一個簡單應用

可以根據路由切換瀏覽器的title屬性,對props.history進行監聽,切換路由的時候獲取當前的路由路徑,同時可以根據不同的路由設置不同的瀏覽器title標題。

仍然是App.js組件:

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)=>{ //在這裏監聽location對象 console.log(location.pathname); //切換路由的時候輸出"/one/users"和"/one/companies" switch(location.pathname){ //根據路徑不同切換不同的瀏覽器title case ‘/one/users‘ : document.title = ‘用戶列表‘; break; case ‘/one/companies‘ : document.title = ‘公司列表‘; break; default : break; } }) } render(){ return (<div className=‘app‘> <NavLink to=‘/one/users‘>用戶列表</NavLink> <NavLink to=‘/one/companies‘>公司列表</NavLink> <Switch> <Route path=‘/one/:type?‘ component={One} /> <Redirect from=‘/‘ to=‘/one‘ exact /> <Route component={NotFound} /> </Switch> </div>) } } export default withRouter(App);

頁面效果:

技術分享圖片

當點擊“用戶列表”,瀏覽器標題會顯示:技術分享圖片

當點擊“公司列表”,瀏覽器標題會顯示:技術分享圖片

三:當然還有眾多用途,如果你使用了編程式導航的寫法:

this.props.history.push(‘/detail‘) 去跳轉頁面,但是報 this.props.history 錯誤 undefined,請在此組件中使用 withRouter 將 history 傳入到 props上。

withRouter的作用和一個簡單應用