应用程序在帧中调用API时崩溃Processor React Native

llmtgqce  于 2022-12-30  发布在  React
关注(0)|答案(1)|浏览(246)

我在React Native应用程序中使用名为vision-camera-code-scanner的依赖项进行QR码扫描。我可以正确获取QR码扫描数据。但我需要传递该数据以进行API调用。但当我尝试这样做时,应用程序崩溃。不确定我应该在这里做什么。
下面是我的组件:

import React, { useState, useCallback, useEffect, useMemo } from "react";
import { StyleSheet, Text } from "react-native";
import {
  Camera,
  useCameraDevices,
  useFrameProcessor,
} from "react-native-vision-camera";
import { useDispatch, useSelector } from "react-redux";
import * as appActions from "../../../redux/app/app.actions";
import { BarcodeFormat, scanBarcodes } from "vision-camera-code-scanner";

interface ScanScreenProps {}

const Scan: React.FC<ScanScreenProps> = () => {
  const [hasPermission, setHasPermission] = useState(false);
  const devices = useCameraDevices();
  const device = devices.back;
  const dispatch = useDispatch();
  const validateQRStatus = useSelector(validationQRSelector);

  const frameProcessor = useFrameProcessor((frame) => {
    "worklet";
    const detectedBarcodes = scanBarcodes(frame, [BarcodeFormat.QR_CODE], {
      checkInverted: true,
    });
    if (detectedBarcodes?.length !== 0) {
        const resultObj = JSON.parse(detectedBarcodes[0].rawValue);
        const paramData = `token:${Object.values(resultObj)[0]}`;
        validate(paramData);
  }, []);

  const validate = useCallback((param: string) => dispatch(appActions.validateQR(param)));

  useEffect(() => {
    (async () => {
      const status = await Camera.requestCameraPermission();
      setHasPermission(status === "authorized");
    })();
  }, []);

  return (
    device != null &&
    hasPermission && (
      <>
        <Camera
          style={StyleSheet.absoluteFill}
          device={device}
          isActive={true}
          frameProcessor={frameProcessor}
          frameProcessorFps={5}
        />
        {/* {barcodes.map((barcode, idx) => (
          <Text key={idx} style={styles.barcodeTextURL}>
            {barcode.barcodeFormat + ": " + barcode.barcodeText}
          </Text>
        ))} */}
        <Text style={styles.barcodeTextURL}>camera</Text>
      </>
    )
  );
};

export default Scan;

const styles = StyleSheet.create({
  barcodeTextURL: {
    fontSize: 20,
    color: "white",
    fontWeight: "bold",
    alignSelf: "center",
  },
});
vnjpjtjt

vnjpjtjt1#

你的问题是一个worklet在一个单独的JS线程中运行,如果你需要从你的主线程调用任何函数,你需要使用runOnJShttps://docs.swmansion.com/react-native-reanimated/docs/next/api/miscellaneous/runOnJS/

import { runOnJS } from 'react-native-reanimated';

  const frameProcessor = useFrameProcessor((frame) => {
    "worklet";
    const detectedBarcodes = scanBarcodes(frame, [BarcodeFormat.QR_CODE], {
      checkInverted: true,
    });
    if (detectedBarcodes?.length !== 0) {
        const resultObj = JSON.parse(detectedBarcodes[0].rawValue);
        const paramData = `token:${Object.values(resultObj)[0]}`;
        runOnJS(validate)(paramData);
  }, []);

相关问题