如何优雅地防止 React Native 崩溃?

TIM*_*MEX 5 javascript error-handling react-native

我想在发生任何错误(语法、未定义、类型错误等)时优雅地显示一个空视图

这是我尝试过的,但它似乎并没有优雅地失败。此实现后整个应用程序仍然崩溃。

const Parent = (props) => {
    try{
        return (<Child/>) //if Child logic crashes for any reason,  return a blank view.
    }catch(err){
        return <View/>
    }
}
Run Code Online (Sandbox Code Playgroud)

Vas*_*iak 2

您可以使用ErrorBoundary https://reactjs.org/docs/error-boundaries.html

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}
Run Code Online (Sandbox Code Playgroud)

在根项目中使用(示例App.js

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>
Run Code Online (Sandbox Code Playgroud)