首页 > 解决方案 > 使用材料 ui 弹出框反应错误边界意外行为

问题描述

弹出框内有一个通知组件,可以进行 fetch 调用。

连接失败,无法访问资源。

错误边界组件包装了通知组件。

预计连接失败后,将显示一个自定义组件,显示出现问题以及重试连接的按钮。

但是,错误边界的行为是:它在弹出框打开时暂停(未显示任何内容),然后在它关闭前几分钟,它显示自定义组件以重试连接并且弹出框完成关闭。

export default function PopOver() {
  const [anchorNotificationEl, setAnchorNotificationEl] = React.useState(null);
  const popoverNotiRef = React.useRef(null);

  const isNotificationOpen = Boolean(anchorNotificationEl);

  const handleClick = (event) => {
    setAnchorNotificationEl(event.currentTarget);
  };

  const handleNotificationClose = () => {
    setAnchorNotificationEl(null);
  };

  const notificationId = 'notification-popover';
  return (
    <>
      <IconButtonCustom
        aria-label="show 17 new notifications"
        color="inherit"
        onClick={handleClick}
        id="notifications-icon"
      >
        <Badge
          badgeContent={0}
          color="secondary"
        >
          <NotificationsIcon
            fontSize="large"
          />
        </Badge>
      </IconButtonCustom>
      <Popover
        ref={popoverNotiRef}
        id={notificationId}
        open={isNotificationOpen}
        anchorEl={anchorNotificationEl}
        onClose={handleNotificationClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'center',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        elevation={1}
      >
        <Notifications popoverRef={popoverNotiRef.current} />
      </Popover>
    </>
  );
}
class ErrorBoundary extends React.Component <Props, State> {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }

  static getDerivedStateFromError(error): State {
    return { error };
  }

  componentDidCatch(error) {
    this.setState({ error });
  }

  render() {
    const { children, fallback } = this.props;
    const { error } = this.state;
    if (error) {
      if (fallback) {
        return fallback;
      }
      return <p>Something is wrong</p>;
    }
    return children;
  }
}

export default function NotificationWrapper({ popoverRef }: NWProps) {
  const [queryReference, loadQuery] = useQueryLoader(NotificationsQuery);

  useEffect(() => {
    loadQuery({
      count: 5,
    }, { fetchPolicy: 'store-and-network' });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <>
      <ErrorBoundary fallback={<RetryComponent loadQuery={loadQuery}/>}>
        {queryReference && (
        <Suspense fallback={<Loading />}>
          <NotificationsIntermediate queryRef={queryReference} popoverRef={popoverRef} />
        </Suspense>
        )}
      </ErrorBoundary>
    </>
  );
}

标签: javascriptreactjserror-handlingmaterial-uirelaymodern

解决方案


推荐阅读