淺談react傳入路由參數---withRouter組件


作用:

默認情況下必須經過路由匹配渲染的組件才存在this.props,才擁有路由參數,執行this.props.history.push('/detail')跳轉到對應路由的頁面,然而不是所有組件都直接與路由相連(通過路由跳轉到此組件)的,當這些組件需要路由參數時,使用withRouter就可以給此組件傳入路由參數,將react-router的history、location、match三個對象傳入props對象上,此時就可以使用this.props。

 

小結:

  

 

 

如何使用:

比如app.js這個組件,一般是首頁,不是通過路由跳轉過來的,而是直接從瀏覽器中輸入地址打開的,如果不使用withRouter此組件的this.props為空,沒法執行props中的history、location、match等方法。

使用時可以通過下面兩種方式:

1.在要注入屬性的組件上使用'@withRouter'

2.類似‘withRouter(App)’

import React,{Component} from 'react'
import {Switch,Route,NavLink,Redirect,withRouter} from 'react-router-dom' //引入withRouter
import One from './One'
import NotFound from './NotFound'
/*或者直接在組件上使用‘@withRouter’*/
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標題。

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);
 
          
        
 
【問題】
  雖然可以實現自動選中當前菜單項,但仍然存在問題,如下所示
  如果請求路徑為根路徑,則如下所示
  

  先找到的是/,然后再重定向到/home,因為之前是用的根路徑重定向,如下

  

  將其改為動態的即可

  

 

  

 

 
 
 

 




免責聲明!

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



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