如何在 Reactjs 中抛出错误而不是从 proptypes 发出警告?

How to throw error instead of warning from proptypes in Reactjs?

当我们在 reactjs 中有任何无效的 prop 类型时,我们通常会在控制台上收到警告。 但我想向开发人员或用户显示错误,以便它变得清晰,用户需要优先修复它。 有没有办法在主屏幕上而不是在控制台上抛出错误?

原因是,在我的代码中有一个未定义的对象数组,因为它没有被传递,我已经在 proptypes 中应用了检查,但它出现在控制台中。 我需要某种弹出窗口,以便用户清楚地了解数据不可用。

而不是下面的屏幕:

官方的方法是实现一个ErrorBoundary,捕获错误,并为其渲染一个特定的UI元素。

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

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; 
  }
}