react 如何监听路由变化

发布于 2022-09-06 09:17:53 字数 171 浏览 17 评论 0

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北城孤痞 2022-09-13 09:17:53

分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', () => {

})
世态炎凉 2022-09-13 09:17:53
componentDidMount() {
    this.context.router.history.listen((route) => {
        if(route.pathname === '/xxx') {
            console.log(1);
        }
    });
}
如梦亦如幻 2022-09-13 09:17:53

componentWillUpdate(nextProps) 或者 componentDidUpdate(prevProps)

componentWillUpdate(nextProps) {
    if (this.props.location !== nextProps.location) {
      // 路由变化
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文