简体   繁体   English

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

[英]Interval inside React useEffect - store it in a useRef Hook to preserve value overtime warning

So I have this method: 所以我有这个方法:

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]);

Now it throws an error where it says: 现在它抛出一个错误,它说:

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.

I am confused on what does this mean? 我很困惑这是什么意思? especially this part: To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property . 特别是这部分: To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property

The error is pointing you to the right direction. 错误指向正确的方向。 Use the useRef hook to reference the video element. 使用useRef钩子来引用视频元素。 Since the handleVideo function makes the dependencies of useEffect Hook change on every render we wrap the handleVideo definition into its own useCallback() Hook. 由于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" />
}

try this way it will be work 试试这种方式它会起作用

const video = useRef(null);
const videoPlay = () => { //just hate stateFull Function
        video.current.play();
      }
useEffect(() => {
    //.. other logic here

    // Firefox doesn't support looping video, so we emulate it this way
    video.addEventListener(
      "ended",
      videoPlay,
      false
    );
    return video.removeEventListener("ended", videoPlay, true)
  }, [videoWidth, videoHeight, video]);
   <video ref={video}>
      <source src={src} type="video/mp4" />
   </video>

if put the code in jsfiddle or some whare like this we can help you more 如果把代码放在jsfiddle或像这样的whare,我们可以帮助你更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM