Skip to content

react 组件监听router变化方法 #2

Description

@lusteng

vue 可以通过对$route 对象的watch来监听路由对象的变化,但是react并没有对这块很好的封装,下面总结在平时的业务中使用的三种方法


  • 使用 history 控制路由跳转

this.props.history.listen(location => {
      // 路由变化了,do something
});
  • 使用 context history 控制路由跳转 (不太推荐方式)

  • 使用底层hashchange事件监听

window.addEventListener('hashchange', function(e){
   console.log(e.oldURL, e.newURL); 
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions