所以我有这个方法:
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.
我对这是什么意思感到困惑?尤其是这部分:To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property
。
答案 0 :(得分:2)
错误将您指向正确的方向。使用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" />
}
答案 1 :(得分:0)
尝试这种方式会起作用
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>
如果将代码放入jsfiddle或类似的地方,我们可以为您提供更多帮助