路由监听

39 阅读1分钟
(一): 局部路由监听: 
1, 在路由跳转的组件中使用props.history.listen() 监听路由, 得到返回值cancle
this.cancle = props.history.listen((route, type)=>{})
 
2, 在组件的componentWillUnmount中取消路由监听, 调用 cancle函数, 以防止重复监听,浪费性能
this.cancle()

注: 局部监听只能监听此组件离开时的路由, 类似于vue中beforeRouteLeave() 路由守卫


(二): 全局路由监听: 
1, 在app.js中从路由模块导入withRouter 
import { withRouter } from 'react-router-dom'

2, 导出App时,用withRouter 函数处理后导出, 把路由数据添加到props中
export default withRouter(App);

3, 在app根组件的componentDidMount函数中添加全局路由监听
 componentDidMount() {
    console.log(this.props)
    this.props.history.listen(path=>{
      console.log("全局路由监听" + path.pathname)
    })
  }

注: 全局路由监听,根组件App中没有路由信息, 需要使用高阶组件withRouter添加路由信息,然后监听