react-错误时直接白屏怎么办---错误边界

2023-12-21  本文已影响0人  Biao_349d

参考链接 https://www.51cto.com/article/769003.html

import React from "react";
import {Text} from 'react-native'

class ErrorBoundary extends React.Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }
  
    static getDerivedStateFromError(error) {
      // 更新 state,下一次渲染将展示备选 UI。
      console.log(`ErrorBoundary---error---`, error)
      return { hasError: true };
    }
  
    componentDidCatch(error, errorInfo) {
      console.log(error, errorInfo);
    }
  
    render() {
      if (this.state.hasError) {
        // 可以渲染任意自定义的备选 UI
        return <Text>出错啦!</Text>;
      }
  
      return this.props.children; 
    }
  }

  export default ErrorBoundary;

上一篇 下一篇

猜你喜欢

热点阅读