react-router-dom4.x withRouter用法及函数式路由跳转

作用:将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等方法, 如: 函数式跳转this.props.push('/detail')

设置withRouter很简单只需要两步:1引入, 2执行, 如下

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'>HOME</NavLink>
            <NavLink to='/one/companies'>OTHER</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 = 'HOME'; 
                      	break;
                      case '/one/companies' : 
                      	document.title = 'OTHER'; 
                      	break;
                      default : break;
              }
           })
   }
   render(){
     return (
     <div className='app'>
       <NavLink to='/one/users'>HOME</NavLink>
       <NavLink to='/one/companies'>OTHER</NavLink>
       <Switch>
         <Route path='/one/:type?'  component={One} />
         <Redirect from='/' to='/one' exact />
         <Route component={NotFound} />
       </Switch>
     </div>
     )
   }
}
export default withRouter(App);

你可能感兴趣的:(react)