如何避免在Android中重新渲染相机?

时间:2020-03-15 21:40:46

标签: javascript reactjs react-native

所以问题是使用react-native-qrcode-scanner,当我在应用程序的选项卡之间切换时,QR扫描仪在Android中变黑。我读了它,因为在Android中这些组件不会卸载。我必须添加一个isFocused if语句,但它会导致整个事件重新呈现,并且会带来可怕的用户体验。有没有if语句可以使它更好的方法?谢谢!

import { withNavigationFocus } from 'react-navigation';

class ScannerScreen extends Component {
  ...
  const { isFocused } = this.props
  ...

  {isFocused ? 
    <QRCodeScanner
      showMarker={true} 
      vibrate={false}
      ref={(camera) => {this.state.scanner = camera}}
      cameraStyle={{overflow: 'hidden', height: QRHeight}}
      onRead={read}
      bottomContent={<BottomQRScanner/>}
    />
    :
    null
  }
}

export default withNavigationFocus(ScannerScreen)

1 个答案:

答案 0 :(得分:0)

好的,您可以将其添加到componentdidmount / componentwillmount中,并在componentwillunmount或useeffecthook中删除列表器

useEffect(() => {
      const unsubscribe = navigation.addListener('willFocus', () => {
       //Your function that you want to execute
      });

      return () => {
        unsubscribe.remove();
      };
  });

或者在新版本中只需执行

从“反应导航”中导入{NavigationEvents};

与此

<NavigationEvents onDidFocus={() => console.log('I am triggered')} />

onDidFocus事件将在页面聚焦时被调用。