今天在使用react-router setRouteLeaveHook的鈎子函數,不知道怎么實驗就是成功。最后功夫不負有心人,終於讓我找到使用setRouteLeaveHook的方法了
1、我在網絡上找到關於如何使用的方法,
componentDidMount(){
this.props.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
)
}
routerWillLeave=(nextLocation)=>{
return '確認要離開?';
}
但是,歐額,要報錯

無法找到props里面的router,
廢了很大的勁,終於找到問題所在,
原因:
缺少react-router的 withRouter方法加工一下組件,所以找不到props里面的router
解決辦法:
1、在組件頭部引入react-router模塊,要導入withRouter
import { withRouter } from 'react-router'
2、在導出組件的時候,通過withRouter方法對組件進行加工
export default withRouter(Login)
代碼編譯好之后,重新進入到頁面,路由跳轉就會出現提示

