将在组件卸载时自动响应删除事件侦听器



当组件卸载时,反应会自动删除事件侦听器,还是我必须在componentWillUnmount()中删除它们?

我特别指的是注册到实际组件的呈现内容的事件侦听器。

不手动删除它们是不好的做法吗?

例:

import React, { Component } from 'react';
import { render } from 'react-dom';
class App extends Component {
  constructor() {
    super();
  }
  componentDidMount() {
    this.content.addEventListener('click', () => alert('Hello'));
  }
  setRef = ref => {
    this.content = ref;
  }
  render() {
    return (
      <div ref={this.setRef}>
        <p>Hello World</p>
      </div>
    );
  }
}
render(<App />, document.getElementById('root'));

卸载组件时,<div>元素将从 DOM 中删除。如果从 DOM 中删除该元素,则也会删除其所有事件侦听器。

当组件卸载时,反应会自动删除事件侦听器吗?

不,它没有。

我必须在componentWillUnmount()中删除它们吗?

是的,这是正确的方法。否则,您可能会收到错误。下面是在组件卸载时未正确删除的事件的回调中调用setState()时将收到的错误示例:

Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

以下是解决此问题的方法:

componentDidMount() {
  this.content.addEventListener('click', this.myFunc);
}
componentWillUnmount() {
  this.content.removeEventListener('click', this.myFunc);
}
myFunc = () => {
  alert('Hello')
}

您必须使用 componentWillUnmount 方法删除事件侦听器,否则可能会出现内存泄漏,这可能会导致浏览器崩溃或无响应。

处理点击事件的推荐方法如下;

import React, { Component } from 'react';
import { render } from 'react-dom';
class App extends Component {
  handleClick() {
    alert('Alert!');
  }
  render() {
    return (
      <div onClick={this.handleClick.bind(this)}>
        <p>Hello World</p>
      </div>
    );
  }
}
render(<App />, document.getElementById('root'));

最新更新