简体   繁体   中英

jump to specific time in videojs using react hooks

I am trying to implement feature to jump 15 seconds forward or backward in video.

I am facing hard time to set the update and set the current time.

const videoNode = useRef(null);
  const [currentTime, setCurrentTime] = useState(null);

  const handleTimeJump = (type) => {
    const player = videojs(videoNode.current);
    console.log(player)
    if (player) {
      type === 'inc' && setCurrentTime(player.currentTime() + 15);
      player.currentTime() > 15 ? setCurrentTime(player.currentTime() - 15) : setCurrentTime(0)
    }
  };

  useEffect(() => {
    const player = videojs(
      videoNode.current,
      videoJsOptions,
      function onPlayerReady() {
        console.log('onPlayerReady');
        player.on('timeupdate', () => {
          setCurrentTime(player.currentTime());
        });
      },
    );
    if (!videoJsOptions.sources[0].src) {
      console.log('no source found');
    }
    return () => {
      if (player) {
        player.dispose();
      }
    };
  }, []);

  useEffect(() => {
    const player = videojs(videoNode.current)
    player.currentTime(currentTime)
}, [currentTime])

handleTimeJump is called after clicking a button.

onClick={() => handleTimeJump('inc')}

Look I haven't tested if it works but looks like it should be player.setCurrentTime(currentTime) instead of player.currentTime(currentTime)

If that works then they should have thrown an error when calling currentTime with an argument because it is not supposed to take an argument (*cough* or you could use a statically typed language *cough*)

Also the currentTime state is already in the videojs-land there's no need to create another in React-land and keep them in sync. You're dispatching a react update EVERY SECOND. Here's a higly recommended and unsolicited refactor (keeping diff as less as possible):

const videoNode = useRef(null);
const playerRef = useRef(null);
const player = playerRef.current;

const handleTimeJump = (type) => {
  if (player) {
    type === 'inc' && player.setCurrentTime(player.currentTime() + 15);
    player.currentTime() > 15 ? player.setCurrentTime(player.currentTime() - 15) : player.setCurrentTime(0)
  }
};

useEffect(() => {
  playerRef.current = videojs(
    videoNode.current,
    videoJsOptions
  );
  if (!videoJsOptions.sources[0].src) {
    console.log('no source found');
  }
  return () => {
    if (player) {
      player.dispose();
    }
  };
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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