反应:history.listen-如何取消监听?

问题描述 投票:0回答:1

在一个模块上,我需要听url的变化,所以我写了一个简单的代码:

componentDidMount(){
        history.listen( location =>  {
            console.log('listen')
            doSomeStuff(location);
        });
    }

但是离开使用该模块的页面后,我仍然看到console.log('listen),事实证明,即使没有必要,侦听器仍会执行功能doSomeStuff(location)

我阅读了引用说明的文档:

“当您使用history.listen附加侦听器时,它将返回一个可用于删除该侦听器的函数,然后可以在清除逻辑中调用该函数:”

const unlisten = history.listen(myListener);
// ...
unlisten();

我不明白我需要在ComponentWillUnmount中写什么才能停止此侦听器。

我正在使用2.8.0react-router版本>>

[在一个模块上,我需要听url的变化,所以我写了一个简单的代码:componentDidMount(){history.listen(location => {console.log('listen')doSomeStuff(...

reactjs react-router
1个回答
0
投票

您需要将unlistener函数存储在类中的变量中,以便可以从其他事件中调用它

YourClass extends React {

  // ..
  componentDidMount() {
    this.unregisterHistoryListener = history.listen( location =>  {
      console.log('listen')
      doSomeStuff(location);
    });
  }

  componentWillUnmount(){
    this.unregisterHistoryListener()
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.