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

标签 javascript reactjs create-react-app intervals 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]);

现在它抛出一个错误:

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.

我不明白这是什么意思?尤其是这一部分:要随时间保留值,将其存储在 useRef Hook 中并将可变值保留在“.current”属性中

最佳答案

错误为您指明了正确的方向。使用 useRef 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" />
}

关于javascript - React useEffect 中的间隔 - 将其存储在 useRef Hook 中以保留值超时警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57084113/

相关文章:

javascript - React 应用返回 500 Internal Server Error

javascript - 使用按钮单击来修改 html 元素

reactjs - 将 Redux 存储中的值从父组件传递给许多子组件

reactjs - 使用 Enzyme 进行测试时使用 React Hooks 访问功能组件的状态

javascript - 无法获取指针字段值的值 Parse + React

https - create-react-app https localhost 安全连接失败

node.js - 在 WebStorm 中创建 react 应用程序

javascript - 有没有办法将事件绑定(bind)到 JavaScript 中的常规对象?

javascript - 如何处理 Electron 中的 blob 数据?

javascript - 如何使用 jQuery 图像轮播