0

我正在尝试使用 ErrorBoundary 来捕获我的应用程序中的潜在错误。我能够看到该ErrorBoundary组件一秒钟,然后我的应用程序崩溃了。

它似乎发生在原始组件第二次引发错误时。

这是我的组件:

const Confirmation = () => {
  const { spot, checkout } = useSelector((state: RootState) => state);
  const history = useHistory();
  const params = useParams<{ id: string }>();
  const dispatch = useDispatch();

  const onPurchaseAnotherClick = () => {
    history.push("/");
  };

  useEffect(() => {
    if (!checkout.order) {
      dispatch(getReservation(params.id));
    } else if (!spot.selected) {
      dispatch(loadSpecificSpot(checkout.order?.spotId));
    }
  }, [dispatch, params, checkout.order?.spotId]);

  if (checkout.notFound) {
    throw new Error("I crashed!");
  }

  if (!spot.selected || !checkout.order) {
    return null;
  }

  return (
    <div className='Confirmation'>
    </div>
  );
};

和我的错误边界

import React from "react";

class ErrorBoundary extends React.Component {
  state = { error: false, errorInfo: null };

  componentDidCatch(error: any, errorInfo: any) {
    this.setState({ hasError: true, errorInfo });
    // Log error
    console.log(error);
  }

  render() {
    if (this.state.errorInfo) {
      return (
        <div className='Confirmation'>
          Something went wrong... <a href='/'>Go back</a>
        </div>
      );
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

知道我做错了什么。顺便说一句,我正在使用反应 17.0.1

4

0 回答 0