繁体   English   中英

在React.js中,使用componentWillUnmount删除事件监听器,如何确保事件监听器被删除?

[英]In React.js, using componentWillUnmount to remove an event listener, how can I make sure the event listener gets removed?

卸载组件后,调整窗口大小时出现错误。 我知道window.removeEventListener正在被调用,但它的行为好像从未被调用过。 错误提示:

warning.js:36警告:setState(...):只能更新已安装或正在安装的组件。 这通常意味着您在未安装的组件上调用了setState()。 这是无人值守。 请检查HeaderMain组件的代码。

我什至尝试使用React文档中的代码示例,它做我的课堂正在做的事情。 来自https://facebook.github.io/react/tips/dom-event-listeners.html

import React from "react";

var HeaderMain = React.createClass({
  getInitialState: function() {
    return {windowWidth: window.innerWidth};
  },

  handleResize: function(e) {
    this.setState({windowWidth: window.innerWidth});
  },

  componentDidMount: function() {
    window.addEventListener('resize', this.handleResize);
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleResize);
  },

  render: function() {
    return <div>Current window width: {this.state.windowWidth}</div>;
  }
});

module.exports = HeaderMain;

我已经尝试过使用bind() ,我已经在ES6尝试,并尝试了不同版本的React.js 我无法摆脱错误。

如何确保事件监听器将被删除?

我发现这与绑定有关。 当您调用.bind(this)时,它将返回具有所需作用域的新函数,因此它并未取消注册我认为我添加的相同函数。

另外,由于某种原因,我发现在ES6 + React v15.3.1(最新版本)中不会像在ES5(React的相同版本)中那样发生自动绑定(我认为应该如此),所以我只存储了引用绑定函数,然后重用它。

import React from "react";

export default class HeaderMain extends React.Component {

  boundFunc = this.handleResize.bind(this);

  constructor()
  {
    super();

    this.state = {height:window.innerHeight + "px"};
  }

  handleResize(e)
  {
    this.setState({height:window.innerHeight + "px"});
  }

  componentDidMount()
  {
     window.addEventListener('resize', this.boundFunc);
  }

  componentWillUnmount()
  {
    window.removeEventListener('resize', this.boundFunc);
  }

  render() {

    return (
      <header class="header_main" style={{height:this.state.height}}>
         Example Header
      </header>
    );
  }
}

不用担心这个警告,您可以在handleresize函数中使用console.log()进行测试,如下所示:

 handleResize: function(e) {
    this.setState({windowWidth: window.innerWidth} , function(){
    console.log("windowWidth" , windowWidth);
    });
  }

使用更改路由或执行任何操作来测试它,以调用componentWillUnmount函数,然后打开console并调整大小窗口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM