在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中路由鉤子的兩種用法,固然重點放在了第二種在組件內部使用的狀況。
看看就好,只是作個記錄。