メインコンテンツにスキップ

エラー境界

オプション 1: react-error-boundary の使用

React-error-boundary - このシナリオで TS サポートを組み込んで使用できる軽量パッケージです。このアプローチでは、現在あまり人気のないクラスコンポーネントを避けることもできます。

オプション 2: カスタムエラー境界コンポーネントを作成する

これに対して新しい npm パッケージを追加したくない場合は、独自に ErrorBoundary コンポーネントを作成することもできます。

import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props {
children?: ReactNode;
}

interface State {
hasError: boolean;
}

class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false
};

public static getDerivedStateFromError(_: Error): State {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}

public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error("Uncaught error:", error, errorInfo);
}

public render() {
if (this.state.hasError) {
return <h1>Sorry.. there was an error</h1>;
}

return this.props.children;
}
}

export default ErrorBoundary;

付け加えることがありますか? 問題を提起する.