【问题标题】:How to use React error boundary with promises如何使用带有 Promise 的 React 错误边界
【发布时间】:2020-06-25 09:51:19
【问题描述】:

我正在尝试为 React 应用程序中的任何未处理异常实现通用错误页面。但是,错误边界似乎不适用于 API 操作等 Promise 引发的异常。我知道我可以在组件级别捕获异常并在渲染方法中重新抛出它。但这是我想避免的样板。如何在 promise 中使用错误边界?

我正在使用带有钩子和 react-router 的最新 React 进行导航。

【问题讨论】:

    标签: javascript reactjs promise react-router react-hooks


    【解决方案1】:

    您可以通过创建一个 HOC 来实现,该 HOC 将采用两个参数第一个是组件,第二个是承诺。它会返回响应并加载到道具中请在下面找到代码供您参考。

    HOC

    import React, { Component } from "react";
    function withErrorBoundary(WrappedComponent, Api) {
      return class ErrorBoundary extends Component {
        constructor(props) {
          super(props);
          this.state = { hasError: false, response: null, loading: false };
        }
        async componentDidMount() {
          try {
            this.setState({
              loading: true
            });
            const response = await Api;
    
            this.setState({
              loading: false,
              response
            });
            console.log("response", response, Api);
          } catch (error) {
            // throw error here
            this.setState({
              loading: 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
        }
    
        render() {
          if (this.state.hasError) {
            // You can render any custom fallback UI
            return <h1>Something went wrong.</h1>;
          }
    
          return (
            <WrappedComponent
              response={this.state.response}
              loading={this.state.loading}
              {...this.props}
            />
          );
        }
      };
    }
    export default withErrorBoundary;
    

    如何使用 HOC

    import ReactDOM from "react-dom";
    import React, { Component } from "react";
    import withErrorBoundary from "./Error";
    
    class Todo extends Component {
      render() {
        console.log("this.props.response", this.props.response);
        console.log("this.props.loading", this.props.loading);
        return <div>hello</div>;
      }
    }
    const Comp = withErrorBoundary(
      Todo,
      fetch("https://jsonplaceholder.typicode.com/todos/1").then(response =>
        response.json()
      )
    );
    
    ReactDOM.render(<Comp />, document.getElementById("root"));
    
    

    请查看codesandbox 以供参考

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 2019-02-20
      • 2021-08-09
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 2021-11-30
      相关资源
      最近更新 更多