【问题标题】:Video pausing unexpectedly when video `onTimeUpdate` event is called (with React Hooks)调用视频“onTimeUpdate”事件时视频意外暂停(使用 React Hooks)
【发布时间】:2020-11-21 21:08:05
【问题描述】:

代码

这是视频元素:

    <video
      ref={videoRef}
      onDurationChange={onSetVideoDuration}
      onTimeUpdate={onSetVideoTimestamp}
      width="100%"
      controls
    >

函数onSetVideoTimestamp是用来设置视频时间戳状态变化时的:

  const onSetVideoTimestamp = (event: SyntheticEvent<HTMLVideoElement, Event>) => {
    const timestamp = event.currentTarget.currentTime
    setVideoTimestamp(Math.floor(timestamp))
  }

这就是 videoTimestampsetVideoTimestamp 的声明方式:

const [videoTimestamp, setVideoTimestamp] = useState(0)

什么是有效的

基本上,上面的代码工作,这意味着时间戳状态设置正确。

问题

  • 问题在于,由于视频正在播放,时间戳状态会不断更新,这会导致视频始终暂停和取消暂停。总之,视频再现并不流畅。

  • 另一个问题是,如果我设置为每 60 秒更新一次状态,使用以下代码:

  const onSetVideoTimestamp = (event: SyntheticEvent<HTMLVideoElement, Event>) => {
    if(event.currentTarget.currentTime > videoTimestamp + 60) {
       const timestamp = event.currentTarget.currentTime
       setVideoTimestamp(Math.floor(timestamp))
    }
  }

STILL视频在播放 60 秒后暂停和取消暂停 - 在那一刻。

【问题讨论】:

    标签: reactjs react-hooks react-state


    【解决方案1】:

    如果状态已更新,组件将重新呈现。并且您不断更新组件的状态。这就是您的视频播放不流畅的原因。您应该避免如此频繁地更新它。 一种解决方法是使用视频的currentTime获取当前时间:

    const currentTime = htmlMediaElement.currentTime;
    htmlMediaElement.currentTime = 35;
    

    要访问视频,您可以使用useRef

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多