在react项目中使用react-router的时候,常常遇到须要使用路由钩子的状况。react
路由钩子的使用主要是两种状况:数组
一是进入路由浏览器
二是离开路由react-router
而路由钩子的使用也有两种状况。函数
注:本博客只适用于react-router v3版本this
第一种:onEnter 和 onLeavespa
onEnter能够指定一个函数,它会在进入这个路由的时候执行这个函数code
onLeave指定的函数会在离开路由的时候执行component
const enterTab = () => { console.log('进入路由作一些事情,嘿嘿嘿') }
const leaveTab = () => {
console.log('要离开路由了')
}
<Router history={browserHistory}> <Route path='/' component={App}> <Route path='map' component={Map} onEnter={enterTab.bind(this)} onLeave={leaveTab.bind(this)}></Route> </Route> </Router>
不过这种路由钩子只能在定义路由的时候使用,要想在组件内部控制路由钩子就须要第二种用法router
第二种:react-router的内置高阶组件withRouter
能够经过高阶组件withRouter对当前组件进行‘升级’(给当前组件添加另外的props至关于混入mixin),withRouter会给当前组件一个props属性router,而router有一个setRouteLeaveHook的方法,该方法能够设置当前路由的离开钩子函数。
图示:withRouter给组件添加的props属性。根据该图能够看出还能经过withRouter来控制路由的跳转
示例代码以下:
import {withRouter} from 'react-router' class Test extends Component { constructor(props) { super(props) } render() { return ( <div></div> ) } routerWillLeave(nextLocation) { console.log('router will go to '+nextlocation) return 'confirm to leave ?' } componentDidMount() { this.props.router.setRouteLeaveHook(this.props.routes, this.routerWillLeave) } export default withRouter(Test)
setRouteLeaveHook函数接受两个参数,第一个参数为要监听判断的路由,其应该是一个表示路由的对象,可是this.props.routes多是有多个元素的数组。好比若是当前路由是 '/main/groups' 则this.props.routes就以下图
因此在这种状况下,setRouteLeaveHook函数的第一个参数就应该写成this.props.routes[1]才奏效
而该函数的第二个参数是离开所监测路由的时候要执行的函数,这个函数能够有三种返回值:
小结:本文主要示范了react-router中路由钩子的两种用法,固然重点放在了第二种在组件内部使用的状况。
看看就好,只是作个记录。