繁体   English   中英

在IE11中删除后调用的事件侦听器函数

[英]Event listener function called after it was removed in IE11

我一直在构建组件,听取整个文档的点击,并偶然发现IE11问题。

我写了几个简单的组件来重现这个问题。

 class App extends React.Component { constructor(props) { super(props); this.state = { show: false } } render() { return ( <div> <button onClick={() => this.setState({ show: !this.state.show })} > Toggle </button> <div> {this.state.show && ( <Component /> )} </div> </div> ) } } class Component extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } componentDidMount() { console.log('listener added') document.addEventListener('click', this.handleClick) } componentWillUnmount() { console.log('listener removed') document.removeEventListener('click', this.handleClick) } handleClick() { console.log('clicked!'); const node = ReactDOM.findDOMNode(this); } render() { return <div>Component</div> } } ReactDOM.render( <App /> , document.getElementById('container') ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container"></div> 

因此, Component组件将click监听器添加到文档, App组件负责安装和卸载Component

当安装了Component事件监听器并且卸载了侦听器时,Chrome和Firefox中的所有功能都非常完美。

但是,在IE11中,当删除侦听器时,仍会调用处理程序函数并抛出错误,因为它尝试findDOMNode已卸载组件的findDOMNode 这可能不是一个突破性的问题,但它仍然让我感到困扰,我想知道是否有任何解决方法。

此外,注意 - 通过event.stopPropagation停止传播不是一个选项,因为在我的应用程序Component可以通过多种方式卸载,按钮单击只是一个示例

JSFiddle再现了这个问题

这似乎是IE11中的一个错误。 一些选择:

1。

使用window.addEventListener/window.removeEventListenerdocument.addEventListener/document.removeEventListener应该有效。

2。

我已经看到其他解决方案用isMounted包装处理程序:

if (this.isMounted) {
    const node = ReactDOM.findDOMNode(this);
}

isMounted已被弃用并发出警告。 它被认为是反模式

3。

目前的黑客攻击是创建自己的isMounted 就像是:

componentDidMount() {
    this.mounted = true;
    document.addEventListener('click', this.handleClick)
}

componentWillUnmount() {
    this.mounted = false;
    document.removeEventListener('click', this.handleClick)
}

handleClick() {
    if (this.mounted) {
        const node = ReactDOM.findDOMNode(this);
    }
}

但这只能绕过isMounted控制台警告。

暂无
暂无

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

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