componentDidMount() {
window.addEventListener("scroll", (e) => {console.log("Hello"});
}
componentWillUnmount() {
window.removeEventListener("scroll", (e) => {console.log("Hello"});
}
...do I really need to do window.removeEventListener("scroll", (e) => {console.log("Hello")});
?
Or can I just do window.removeEventListener("scroll", ()=> {});
(with an empty function)? I don't understand why, when removing the eventListener, I need to pass it the exact same anonymous function?
what if I do window.removeEventListener("scroll", ()=> {console.log("Hello2")});
- is this considered a new function now? So will this not remove the original event listener (which has console.log("Hello");
)?
Your componentWillUnmount
function will not remove event listener because the function reference of the event listener which was attached in componentDidMount
is not the same as the one it(compWillUnmount) is trying to remove.
You can check it out by creating and comparing 2 functions in chrome console.
In general, define the eventListener function in your class and attach it in componentDidMount
and remove it in componentWillUnmount
. Since they are executed once, the function reference remains same.
class MyComponent extends React.Component {
...
myEventFun = (e) => {console.log("Hello")};
componentDidMount() {
window.addEventListener("scroll", this.myEventFun);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.myEventFun);
}
...
If you want to deal with adding/removing event listeners in functional component, see this and this
Yes, you have to pass exact same reference, since function is an object and variable holding a reference and function(){} is not equals function(){}
function stuff(){/* your stuff;*/}
window.addEventListener("event",stuff);
window.removeEventListener("event",stuff);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.