如何从正在卸载的背景中删除事件侦听器?

我有一个Backdrop_DIV基于open下拉组件的a 呈现的。


{open &&

  <LS.Backdrop_DIV

    onClick={handleBackdropClick}

    ref={backdrop_ref}

  >

    Backdrop

  </LS.Backdrop_DIV>

}

Backdrop_DIV如果用户滚动 ( touchmove),我希望它消失。


Obs:这是一个移动视图。


const handleTouchMove = useCallback(()=>{

    setOpen(false);

  },[]);

useEffect(() => {

    if (open) {

      // ATTACHING THE EVENT LISTENR

      backdrop_ref.current.addEventListener('touchmove', handleTouchMove );

    }


    // ATTEMPT TO REMOVE THE EVENT LISTENER

    return () => 

      backdrop_ref.current.removeEventListener('touchmove', handleTouchMove);


},[open,handleScroll]);

它有效,但如果在我尝试清除我的useEffect. 有没有办法做到这一点?


错误:


react-dom.development.js:20313 未捕获的类型错误:无法读取 null 的属性“removeEventListener”


这个错误很明显,因为Backdrop_DIV它在运行时不再挂载。



在这种情况下,我需要费心删除事件侦听器吗?我能做什么?


倚天杖
浏览 164回答 1
1回答

皈依舞

根据 Carlene 在评论中推荐的问题,我会说没有必要删除事件侦听器,因为它将由垃圾收集器处理,尽管在这种情况下某些较旧的浏览器可能会泄漏内存。而且,我找到了一种在卸载之前删除侦听器的方法Backdrop_DIV,它可以工作:我添加了lastOpenState_ref&nbsp;useRef()对先前渲染open状态的跟踪,以便我可以检测将卸载Backdrop_DIV(&nbsp;open === false)的渲染,并在该渲染期间移除侦听器。import React, {useState, useEffect, useRef, useCallback} from 'react';function MyComponent() {&nbsp; const [open,setOpen] = useState(false);&nbsp; const backdrop_ref = useRef(null);&nbsp; const lastOpenState_ref = useRef(false);&nbsp; const handleBackdropTouchMove = useCallback(() => {&nbsp; &nbsp; setOpen(false);&nbsp; },[]);&nbsp; // BLOCK TO REMOVE EVENT LISTENER FROM backdrop_ref&nbsp; // SINCE IT'S IMPOSSIBLE TO REMOVE FROM THE useEffect RETURN&nbsp; // BECAUSE THE backdrop_ref IS NULL WHEN IT RUNS&nbsp; if (lastOpenState_ref.current === true && open === false) {&nbsp; &nbsp; backdrop_ref.current.removeEventListener('touchmove', handleBackdropTouchMove);&nbsp; }&nbsp; lastOpenState_ref.current = open;&nbsp; // EFFECT TO ATTACH 'touchmove' EVENT LISTENER ON 'backdrop_ref.current'&nbsp; useEffect(() => {&nbsp; &nbsp; if (open) {&nbsp; &nbsp; &nbsp; backdrop_ref.current.addEventListener('touchmove', handleBackdropTouchMove);&nbsp; &nbsp; }&nbsp; },[open,handleBackdropTouchMove]);&nbsp; // RETURN STATEMENT&nbsp; return(&nbsp; &nbsp; <LS.Container_DIV>&nbsp; &nbsp; &nbsp; {open &&&nbsp; &nbsp; &nbsp; &nbsp; <LS.Backdrop_DIV&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onClick={handleBackdropClick}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ref={backdrop_ref}&nbsp; &nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; </LS.Backdrop_DIV>&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; <SomeOtherStuff/>&nbsp; &nbsp; </LS.Container_DIV>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript