React useEffect 内部的间隔 - 将其存储在 useRef Hook 中以保留值超时警告

I a*_*m L 6 javascript intervals reactjs create-react-app react-hooks

所以我有这个方法:

useEffect(() => {
    //.. other logic here

    // Firefox doesn't support looping video, so we emulate it this way
    video.addEventListener(
      "ended",
      function() {
        video.play();
      },
      false
    );
  }, [videoWidth, videoHeight]);

Run Code Online (Sandbox Code Playgroud)

现在它抛出一个错误,它说:

Assignments to the 'interval' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect.
Run Code Online (Sandbox Code Playgroud)

我很困惑这是什么意思?特别是这部分:To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property

Kam*_*zir 10

该错误为您指明了正确的方向。使用useRef钩子引用视频元素。由于该handleVideo函数使 useEffect Hook 的依赖关系在每个渲染上发生变化,因此我们将定义包装handleVideo到它自己的useCallback()Hook 中。

import React, { useEffect, useRef, useCallback } from "react";

function Video() {
  const videoRef = useRef(null);

  const handleVideo = useCallback(() => {
    videoRef.current.play()
  }, [])

  useEffect(() => {
    const video = videoRef.current
    video.addEventListener('ended', handleVideo)

    return () => {
      video.removeEventListener('ended', handleVideo)
    }
  }, [handleVideo])



  return <video width="400" controls ref={videoRef} src="https://www.w3schools.com/html/mov_bbb.mp4" />
}
Run Code Online (Sandbox Code Playgroud)