2

在我的 componentDidCatch() 方法中捕获错误,并呈现自定义错误 UI。

什么是从错误中继续前进而不是让用户强制更新页面的巧妙方法?

import * as React from "react";

interface ErrorBoundaryState {
    hasError: boolean;
    errorInfo: React.ErrorInfo;
}

export class ErrorBoundary extends React.Component<{}, ErrorBoundaryState> {
    constructor(props: any) {
        super(props);
        this.state = {
            hasError: false,
            errorInfo: undefined,
        };
    }

    public componentDidCatch(error: Error, info: React.ErrorInfo) {
        this.setState({
            hasError: true,
            errorInfo: info
        });
        console.error(error, info);
    }

    public render() {
        if (this.state.hasError) {
            return (
                <h2>Something went wrong, please try again later.</h2>
            );
        }
        return this.props.children;
    }
}

当 hasError 设置为 true 时,它​​会停留在那里。将它设置为 false 并再次向孩子们展示的好地方在哪里?

4

1 回答 1

0

我认为用户想知道为什么被打断了。因此,您可以向用户显示一条错误消息,并告诉他们 5 秒后他可以重新使用该应用程序。

您可以使用 setTimeout 在 5 秒后将状态设置为 hasError:false。

于 2018-06-28T15:24:11.577 回答