React native react本机摄像头条形码扫描仪冻结,因为扫描速度太快

React native react本机摄像头条形码扫描仪冻结,因为扫描速度太快,react-native,react-native-ios,react-native-camera,react-lifecycle,React Native,React Native Ios,React Native Camera,React Lifecycle,我正在尝试使用react-native-camera中的条形码扫描仪。首先,关闭它扫描二维码并提取字符串,然后使用react navigation导航到下一个屏幕。在第二个屏幕中,它进行API调用 现在,如果我回到扫描仪屏幕,de QR码将立即被扫描。这就是我遇到错误的地方,扫描仪冻结了。我通常会遇到这样的错误: Can't call setState (or forceUpdate) on an unmounted component 我想这是因为我的组件willunmount清理工作不正常

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

现在,如果我回到扫描仪屏幕,de QR码将立即被扫描。这就是我遇到错误的地方,扫描仪冻结了。我通常会遇到这样的错误:

Can't call setState (or forceUpdate) on an unmounted component
我想这是因为我的
组件willunmount
清理工作不正常或速度不够快,但我已经取消了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导航错误?

您可以使用标志来控制

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>
    )
  }
}
类QR扩展组件{
建造师(道具){
超级(道具)
此.state={
可扫描:正确
}
this.cameraAttrs={
ref:ref=>{
this.camera=ref
},
style:styles.preview,
类型:RNCamera.Constants.type.back,
条形码类型:[RNCamera.Constants.BarCodeType.qr],
onBarCodeRead:({data})=>{
这个回调(数据)
}
}
}
组件willmount(){
这是正确的
}
组件将卸载(){
这是错误的
}
回调(文本){
如果(!this.state.scanable){
返回
}
console.log(文本)
this.setState({scanable:false})
设置超时(()=>{
如果(本安装){
this.setState({scanable:true})
}
},1000)//1s冷却时间
}
render(){
返回(
)
}
}

我认为您应该使用
clearTimeout()
而不是
\u挂载的
标志。例如,
this.timeout=setTimeout(…)
;然后在
componentWillUnmount
中清除超时:
if(this.timeout){cleartimout(this.timeout)}