首页 文章

react-native-camera条形码扫描仪冻结,因为扫描速度太快

提问于
浏览
0

我正在尝试使用 react-native-camera 的条形码扫描仪 . 首先,关闭它扫描QR码并提取一个字符串,然后用 react-navigation 导航到下一个屏幕 . 在第二个屏幕中,它进行API调用 .

现在,如果我回到扫描仪屏幕,将立即扫描de QR码 . 这就是我遇到错误而扫描仪冻结的地方 . 我经常收到这个错误:

Can't call setState (or forceUpdate) on an unmounted component

我认为这是因为我的 componentWillUnmount 清理不能正常或足够快,但我已经取消了axios请求 .

requestCode = (code) => {
        if (cancel != undefined) {
          cancel();
        }
        axios.get(API_URI + code, {
          cancelToken: new CancelToken(function executor(c) {
            cancel = c;
          })
        }).then(response => {
          console.log(response)
          //checks if code was already called
          this.checkUsed(response.data)
        })
          .catch(error => {
            this.setState({ isValid: false })
          });
        }

    componentWillUnmount() {
        cancel();
      }

也许我可以在稍后安装相机扫描仪,这样它就不会快速扫描,或者甚至可能是React Navigation的错误?

1 回答

  • 0

    您可以使用标志来控制 .

    class QR extends Component {
      constructor(props) {
        super(props)
    
        this.state = {
          scanable: true
        }
    
        this.cameraAttrs = {
          ref: ref => {
            this.camera = ref
          },
          style: styles.preview,
          type: RNCamera.Constants.Type.back,
          barCodeTypes: [RNCamera.Constants.BarCodeType.qr],
          onBarCodeRead: ({ data }) => {
            this.callback(data)
          }
        }
      }
    
      componentWillMount() {
        this._mounted = true
      }
    
      componentWillUnmount() {
        this._mounted = false
      }
    
      callback(text) {
        if (!this.state.scanable) {
          return
        }
    
        console.log(text)
        this.setState({ scanable: false })
        setTimeout(() => {
          if (this._mounted) {
            this.setState({ scanable: true })
          }
        }, 1000) // 1s cooldown
      }
    
      render() {
        return (
          <View style={styles.container}>
            <RNCamera
              {...this.cameraAttrs}
            >
            </RNCamera>
          </View>
        )
      }
    }
    

相关问题