首页 文章

React / React-Router:路由到新页面时未调用componentWillUnmount

提问于
浏览
0

在我使用React-Router的React应用程序中,我有一个这样的Home组件:

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;

但是,当我单击链接,从“/”导航到“/ secondPage”时,它将路由到新页面,但尚未从Home组件中删除事件侦听器 .

根据React-Router docs,似乎应该调用componentWillUnmount .

为什么不调用componentWillUnmount?

2 回答

  • 0

    在添加/删除事件侦听器时,我们必须保持格式相同才能获得预期的结果 . 在您的代码中,您使用此代码添加事件侦听器:

    window.addEventListener("scroll", this.handleScroll, true);
    

    但是为了删除监听器,你使用了这个:

    window.removeEventListener("scroll", this.handleScroll);
    

    我建议你尝试使用这个删除事件监听器 .

    window.removeEventListener("scroll", this.handleScroll, true);
    

    此外,您在打开括号后使用了分号 .

    componentDidMount() {;
    
  • 1

    也许你需要绑定handleScroll?我喜欢使用胖箭头表示法 . handleScroll = (e) => { ... }

相关问题