diff --git a/lib/QRScanner.js b/lib/QRScanner.js index 5ac2d86..b075c4f 100644 --- a/lib/QRScanner.js +++ b/lib/QRScanner.js @@ -281,31 +281,40 @@ export default class QRScannerView extends Component { scanInterval: 2000, userFront: false, }; - + constructor(props){ super(props); // 避免频繁触发扫描回调 this.onScanResult = throttle(this.onScanResult, this.props.scanInterval, { maxWait: 0, trailing: false }); + // 避免rncamera ready之前调用造成闪退 + this.cameraReady = false; } componentDidMount(){ - AppState.addEventListener('change', this.handleAppStateChange); + this.appStateChangeListener = AppState.addEventListener('change', this.handleAppStateChange); } componentWillUnmount(){ - AppState.removeEventListener('change', this.handleAppStateChange); - this.rnCamera && this.rnCamera.pausePreview(); + if (this.appStateChangeListener) { + this.appStateChangeListener.remove(); + } + this.rnCamera && this.cameraReady && this.rnCamera.pausePreview(); } handleAppStateChange = (currentAppState) => { if ( currentAppState !== 'active' ) { - this.rnCamera && this.rnCamera.pausePreview(); + this.rnCamera && this.cameraReady && this.rnCamera.pausePreview(); } else { - this.rnCamera && this.rnCamera.resumePreview(); + this.rnCamera && this.cameraReady && this.rnCamera.resumePreview(); } }; onScanResult = (e) => this.props.onScanResult(e); + + onCameraReady = () => { + this.cameraReady = true; + this.handleAppStateChange(AppState.currentState); + } render(){ const { renderHeaderView, renderFooterView, torchOn, userFront } = this.props; @@ -313,6 +322,7 @@ export default class QRScannerView extends Component { return ( this.rnCamera = ref } + onCameraReady={ this.onCameraReady } captureAudio={ false } onBarCodeRead={ this.onScanResult } type={ userFront ? RNCamera.Constants.Type.front : RNCamera.Constants.Type.back }