首页 > 解决方案 > 是否需要在未安装的元素/组件上删除事件侦听器?

问题描述

如果我将事件侦听器附加到组件,是否需要在卸载时显式删除它?

例如

componentRef = React.createRef();
    handleWheel = (e) => {
      e.preventDefault();
    }
    componentDidMount() {
      if (this.componentRef.current) {
        this.componentRef.current.addEventListener('wheel', this.handleWheel);
      }
    }
    componentWillUnmount() {
      if (this.componentRef.current) {
        this.componentRef.current.removeEventListener('wheel', this.handleWheel);
      }
    }
    render() {
      <Container ref={this.componentRef}>...</Container>
    }

所以我想知道componentWillUnmount在这种情况下是否需要

标签: javascriptreactjs

解决方案


推荐阅读