【问题标题】:React/React-Router: componentWillUnmount not called when routing to new pageReact / React-Router:路由到新页面时未调用componentWillUnmount
【发布时间】:2018-02-23 17:35:59
【问题描述】:

在我使用 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?

【问题讨论】:

  • 您是否通过在此处放置控制台日志进行检查?
  • 是的,我检查过了,它没有调用 componentWillUnmount。
  • 嘿,我面临同样的问题。我已经在下面的链接中发布了这个问题。如果你解决了这个问题,我想听听如何。

标签: reactjs react-router


【解决方案1】:

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

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

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

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

我建议你尝试使用这个来移除事件监听器。

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

另外,您在左大括号后使用了分号。

componentDidMount() {;

【讨论】:

    【解决方案2】:

    也许你需要绑定handleScroll?我喜欢为此使用胖箭头符号。 handleScroll = (e) =&gt; { ... }

    【讨论】:

    • 很遗憾,不是这样——this.handleScroll 绑定正确。
    猜你喜欢
    • 2021-10-21
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2018-04-04
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多