簡體   English   中英

React remove event listener on ref 這也是一個 state 值(性能)

[英]React remove event listener on ref that is also a state value (performance)

我有一個 HTML 音頻元素,它位於 redux state 中(我知道,它就像這樣,所以可以從減速器播放/暫停)。

該音頻被分配給一個useRef

我有一個添加和刪除useEffect事件偵聽器的timeupdate

const {
    isPlaying: { audio, trackNum, playing },
  } = useSelector((state) => state.directory_reducer);

  const audioRef = useRef(audio);

  useEffect(() => {
    if (audio && !spotify_loading) {
      audioRef.current = audio;
      audioRef.current.addEventListener('timeupdate', getProgress);
    }
    return () => {
      setProgressPercent(0);
      setProgressTime(`0:00`);
      !firstRender && audioRef.current.removeEventListener(
        'timeupdate',
        getProgress
      );
    };
  }, [audio]);

問題是,在停止和啟動不同的軌道后,頁面交互變得遲緩,似乎我沒有正確刪除監聽器。 我懷疑這是因為我將 state 值傳遞給 ref,這不是我見過的任何人做的事情。 我也想知道罪魁禍首是否與以下有關:

The returned object will persist for the full lifetime of the component.
...
This works because useRef() creates a plain JavaScript object. The only difference 
between useRef() and creating a {current: ...} object yourself is that useRef will give
you the same ref object on every render.

您必須使用空數組而不是[audio]以便在組件釋放時觸發removeEventListener

 useEffect(()=> { },[])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM