鍍金池/ 問(wèn)答/HTML5  HTML/ react 如何監(jiān)聽(tīng)路由變化

react 如何監(jiān)聽(tīng)路由變化

react-router4 如何監(jiān)聽(tīng)url變化,要通過(guò)url的變化來(lái)做一些 <HashRouter history={hashHistory} onEnter={this.routeUpdate.bind(this)}>
用componentWillReceiveProps也不行,

回答
編輯回答
尋仙

componentWillUpdate(nextProps) 或者 componentDidUpdate(prevProps)

componentWillUpdate(nextProps) {
    if (this.props.location !== nextProps.location) {
      // 路由變化
    }
}
2017年11月5日 13:11
編輯回答
不將就

分2種情況:
1、普通react組件(指不是通過(guò)Route導(dǎo)入的組件)
普通組件需要自己定義上下文

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導(dǎo)入的組件
Route組件已經(jīng)封裝好了上下文,并且設(shè)置了props可用。

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

原生js的辦法是:

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

})
2018年8月27日 02:04
編輯回答
晚風(fēng)眠
componentDidMount() {
    this.context.router.history.listen((route) => {
        if(route.pathname === '/xxx') {
            console.log(1);
        }
    });
}
2017年12月13日 03:45