Reputation: 1136
In my React app that uses React-Router, I have a Home component like this:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class Home extends Component {
componentDidMount() {
window.addEventListener("scroll", this.handleScroll, true);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
handleScroll(e) {
e.preventDefault();
// scroll event handling
}
render () {
return (<div>
// markup
<Link to="/secondPage"></Link>
</div>);
}
}
export default Home;
However, when I click on the Link, navigating from "/" to "/secondPage", it routes to the new page but hasn't removed the event listener from the Home component.
According to the React-Router docs, it seems that componentWillUnmount should be called.
Why is componentWillUnmount not called?
Upvotes: 2
Views: 1558
Reputation: 93
While adding / removing an event listener we must keep the formats same in order to get expected result. In your code, you used this one to add event listener:
window.addEventListener("scroll", this.handleScroll, true);
But for removing the listener, you used this one:
window.removeEventListener("scroll", this.handleScroll);
I suggest you try with this one for removing event listener.
window.removeEventListener("scroll", this.handleScroll, true);
Also, you have used semicolon after the opening braces.
componentDidMount() {;
Upvotes: 1
Reputation: 231
Maybe you need to bind handleScroll? I like using fat arrow notation for that.
handleScroll = (e) => { ... }
Upvotes: 0