react 如何监听路由变化

react-router4 如何监听url变化,要通过url的变化来做一些 <HashRouter history={hashHistory} onEnter={this.routeUpdate.bind(this)}>
用componentWillReceiveProps也不行,

阅读 22.8k
3 个回答

分2种情况:
1、普通react组件(指不是通过Route导入的组件)
普通组件需要自己定义上下文

static contextTypes = {
    router: PropTypes.shape({
      history: PropTypes.shape({
        push: PropTypes.func.isRequired,
        replace: PropTypes.func.isRequired,
        createHref: PropTypes.func.isRequired
      }).isRequired
    }).isRequired
  }
componentDidMount() {
    this.context.router.history.listen(() => {
      
    })
}

2、Route导入的组件
Route组件已经封装好了上下文,并且设置了props可用。

componentDidMount() {
    this.props.history.listen(() => {
      
    })
}

原生js的办法是:

window.addEventListener('hashchange', () => {

})
componentDidMount() {
    this.context.router.history.listen((route) => {
        if(route.pathname === '/xxx') {
            console.log(1);
        }
    });
}

componentWillUpdate(nextProps) 或者 componentDidUpdate(prevProps)

componentWillUpdate(nextProps) {
    if (this.props.location !== nextProps.location) {
      // 路由变化
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题