【问题标题】:Ways to redirect user after componentDidCatch在 componentDidCatch 之后重定向用户的方法
【发布时间】:2018-12-07 17:15:21
【问题描述】:

在我的 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 并再次向孩子们展示的好地方在哪里?

【问题讨论】:

    标签: javascript reactjs error-handling redux react-16


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多