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

如何修复react-barcode-qrcode-scanner组件中的错误?

修复react-barcode-qrcode-scanner组件的useEffect相关错误

1. 补全缺失的renderSVGOverlay函数

代码中JSX部分调用了未定义的renderSVGOverlay(),这是直接触发错误的原因之一,补上该函数:

const renderSVGOverlay = () => {
  if (!props.drawOverlay || barcodeResults.length === 0) return null;
  return (
    <svg viewBox={viewBox} style={{position: 'absolute', top: 0, left: 0, width: '100%', height: '100%'}}>
      {barcodeResults.map((result, index) => (
        <polygon
          key={index}
          points={getPointsData(result)}
          style={{fill: 'rgba(0,255,0,0.2)', stroke: 'green', strokeWidth: 2}}
          onClick={() => onPolygonClicked(result)}
        />
      ))}
    </svg>
  );
};

2. 修复第一个useEffect的依赖与内存泄漏问题

  • 空依赖数组会导致props更新时不重新初始化,同时触发React依赖警告,需将用到的props加入依赖
  • 异步初始化需处理组件卸载后的状态,避免内存泄漏
  • 添加错误捕获,防止初始化失败静默报错

修改后的代码:

React.useEffect(() => {
  let isMounted = true;
  const init = async () => {
    try {
      if (props.license) {
        BarcodeReader.license = props.license;
      } else {
        BarcodeReader.license = "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==";
      }
      if (props.engineResourcePath) {
        BarcodeReader.engineResourcePath = props.engineResourcePath;
      } else {
        BarcodeReader.engineResourcePath = "https://unpkg.com/dynamsoft-javascript-barcode@latest/dist/";
      }
      
      const instance = await BarcodeReader.createInstance();
      if (!isMounted) return;
      
      reader.current = instance;
      
      if (props.runtimeSettings) {
        await instance.initRuntimeSettingsWithString(props.runtimeSettings);
      }
      if (props.onInitialized) {
        props.onInitialized(instance);
      }
    } catch (error) {
      console.error("初始化条码阅读器失败:", error);
    }
  };
  init();
  
  return () => {
    isMounted = false;
    if (reader.current) {
      reader.current.destroy();
      reader.current = null;
    }
  };
}, [props.license, props.engineResourcePath, props.runtimeSettings, props.onInitialized]);

3. 修复第二个useEffect的异步操作问题

调用initRuntimeSettingsWithString是异步函数,需添加await并处理错误:

React.useEffect(() => {
  const updateSettings = async () => {
    if (props.runtimeSettings && reader.current) {
      try {
        await reader.current.initRuntimeSettingsWithString(props.runtimeSettings);
      } catch (error) {
        console.error("更新运行时设置失败:", error);
      }
    }
  };
  updateSettings();
}, [props.runtimeSettings]);

4. 添加全局资源清理逻辑

在组件卸载时确保清理定时器和条码阅读器资源,避免内存泄漏:

React.useEffect(() => {
  return () => {
    stopScanning();
    if (reader.current) {
      reader.current.destroy();
      reader.current = null;
    }
  };
}, []);

5. 类型优化(可选)

去掉不必要的类型断言,reader.current在判断存在后可直接使用,无需(reader.current as BarcodeReader)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 21:19:50