首页 > 解决方案 > 禁用反应原生白屏

问题描述

当应用程序以某种方式崩溃时,我们希望禁用经典白屏。我们正在使用 react-native-exception-handler 模块,它捕获了一些错误,但不是全部。当我们发现这些错误时,我们会通知自己并重新启动应用程序。但有时会出现一些错误(例如,当应用程序从服务器收到一些它不期望的数据时),会触发白屏。我们希望我们的客户保持应用程序冻结或通知他们必须重新启动应用程序,而不是使用“随机”白屏。可以做到吗?

标签: react-native

解决方案


这是一个演示:https ://snack.expo.io/@carloscuesta/react-native-error-boundary

你可以使用react-native-error-boundary

yarn add react-native-error-boundary

这不处理本机错误,但处理 js 级别的所有错误。您可以将此包与 react-native-exception-handler 结合使用。

import * as React from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import ErrorBoundary from 'react-native-error-boundary';

import ComponentWithError from './ComponentWithError'

const App = () => {
  const [isErrorComponentVisible, setIsErrorComponentVisible] = React.useState(false)

  return (
    <ErrorBoundary>
      <View style={styles.container}>
        <Text style={styles.icon}></Text>
        <Text style={styles.title}>
          react-native-error-boundary
        </Text>
        <Text style={styles.text}>
          Click on the following button to render a component that will throw an error.
        </Text>
        <Button title='Throw error' onPress={() => setIsErrorComponentVisible(true)} />
        {isErrorComponentVisible && <ComponentWithError />}
      </View>
    </ErrorBoundary>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
    textAlign: 'center',
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  icon: {
    fontSize: 48
  },
  text: {
    marginVertical: 16
  }
});

export default App

推荐阅读