gpt4 book ai didi

reactjs - React : history. 听 - 如何不听?

转载 作者:行者123 更新时间:2023-12-04 00:02:23 27 4
gpt4 key购买 nike

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

componentDidMount(){
history.listen( location => {
console.log('listen')
doSomeStuff(location);
});
}
但是离开使用这个模块的页面后,还是看到了 console.log('listen) ,原来监听器还是执行了一个函数 doSomeStuff(location) ,即使没有必要?
我读了文档说,引用:

"When you attach a listener using history.listen, it returns a function that can be used to remove the listener, which can then be invoked in cleanup logic:"

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

我不明白我需要在 ComponentWillUnmount 中写什么停止这个监听器。
我正在使用 2.8.0 react-router 的版本

最佳答案

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

YourClass extends React {

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

componentWillUnmount(){
this.unregisterHistoryListener()
}
}

关于reactjs - React : history. 听 - 如何不听?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58526801/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com