【问题标题】:Removing react-router browserHistory change listener删除 react-router browserHistory 更改监听器
【发布时间】:2016-10-21 15:23:10
【问题描述】:

我有一个 react 组件,它使用 browserHistory 的监听方法监听路由变化。在向

注册处理程序后
browserHistory.listen(this.handleRouteChanged)

在ComponentDidMount中,如何移除componentWillUnmount中的监听器?

我找不到任何关于此的文档,并且通过 github 问题搜索我发现使用 browserHistory.unregisterTransitionHook 的建议似乎不会删除侦听器,此外似乎已被弃用。

有什么想法吗?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    listen() 方法返回一个阻止其监听的函数。这记录在history docs

    “历史记录”封装了应用中不同屏幕之间的导航,并在当前屏幕发生变化时通知侦听器。

    import { createHistory } from 'history'
    
    const history = createHistory()
    
    // Get the current location 
    const location = history.getCurrentLocation()
    
    // Listen for changes to the current location 
    const unlisten = history.listen(location => {
      console.log(location.pathname)
    })
    
    // Push a new entry onto the history stack 
    history.push({
      pathname: '/the/path',
      search: '?a=query',
    
      // Extra location-specific state may be kept in session 
      // storage instead of in the URL query string! 
      state: { the: 'state' }
    })
    
    // When you're finished, stop the listener 
    unlisten()
    

    【讨论】:

      猜你喜欢
      • 2017-03-24
      • 2019-06-17
      • 1970-01-01
      • 2017-10-04
      • 2016-04-28
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多