在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

react-router4 如何監(jiān)聽url變化,要通過url的變化來做一些 <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組件(指不是通過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', () => {

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