You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何实现快照URL在一秒内自动切换?

实现快照URL的自动切换效果

你可以通过先设置临时URL,再用定时器延迟切换到目标URL的方式实现需求,具体修改如下:

修改后的代码

import { useState, useEffect, useRef } from 'react';

function CamPreview() {
  const [state, setState] = useState({
    snapshotUrl: "",
  });
  // 用ref存储定时器ID,方便后续清理
  const timeoutRef = useRef(null);

  const updatePreview = () => {
    const allCams=[{identifier: '7-7-7'}]
    const site={identifier: '1-1-1'} 
    const cam={identifier: '0-0-0'} 

    // 第一步:先设置allCams[0]的快照URL
    const tempSnapshot = `api/cam/${site.identifier}/${allCams[0].identifier}/snapshot`;
    setState(prev => ({
      ...prev,
      snapshotUrl: tempSnapshot
    }));

    // 第二步:延迟(比如800毫秒,不足一秒)后切换到cam的URL
    // 先清除之前的定时器,避免多次调用时产生冲突
    if (timeoutRef.current) clearTimeout(timeoutRef.current);
    timeoutRef.current = setTimeout(() => {
      const targetSnapshot = `api/cam/${site.identifier}/${cam.identifier}/snapshot`;
      setState(prev => ({
        ...prev,
        snapshotUrl: targetSnapshot
      }));
      timeoutRef.current = null;
    }, 800); // 可自行调整延迟时长,比如500、800毫秒
  };

  // 组件卸载时清理定时器,防止内存泄漏
  useEffect(() => {
    return () => {
      if (timeoutRef.current) clearTimeout(timeoutRef.current);
    };
  }, []);

  return (
    <div>
      <img src={state.snapshotUrl} alt="摄像头预览" />
      <button onClick={updatePreview}>更新预览</button>
    </div>
  );
}

关键说明

  • 先通过setState设置临时URL,立刻渲染allCams[0]的快照
  • 使用setTimeout延迟执行切换逻辑,时间可根据需求调整(满足"不足一秒"的要求)
  • 用useRef存储定时器ID,确保每次调用updatePreview时先清除之前的定时器,避免多个定时器同时触发
  • 组件卸载时通过useEffect清理定时器,防止内存泄漏

内容的提问来源于stack exchange,提问作者walee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 18:10:29