首页 > 解决方案 > 我们可以在父级中捕获错误但在子级中实现回退 - React Error Boundary

问题描述

我试图在 React 中实现错误边界。这是我的组件

export const withErrorBoundary = WrappedComponent =>
  class extends Component<Props, State> {
    constructor(props) {
      super(props);
      this.state = { error: null, errorInfo: null };
    }

    componentDidCatch = (error, errorInfo) => {
      this.setState({
        error,
        errorInfo,
      });
      // TODO: log error messages, report error
    };

    render() {
      if (this.state.errorInfo) {
        return handleError(this.state.error, this.state.errorInfo);
      }
      // just render children
      return <WrappedComponent {...this.props} />;
    }
  };

const handleError = (error, errorInfo) => (
  <div>
    <h2>Something went wrong.</h2>
    <details>
      {error?.toString()}
      <br />
      {errorInfo.componentStack}
    </details>
  </div>
);

以及我如何使用它

const Parent = () => {
  return (<>
     <div>Fixed Text</>
     <Child /> // --> This component need to replace
    </>

}

export withErrorBoundary(Parent);

所以基本上用这个当前的实现,只要有一些错误Parent,整个Parent将回退到handleError(),(显示“出错了”)

但是,我只希望Child组件被替换,并且<div>Fixed Text</>仍然出现在Parent. 反正有没有改变我的代码来实现这一点?

标签: javascriptreactjs

解决方案


推荐阅读