Error Boundary
ErrorBoudaryの子componentで発生したエラーをcatchして適切に処理するための仕組み
イベントハンドラ・非同期処理・サーバーサイドレンダリング・ErrorBoundary自身のエラー
static getDrivedStateFromErrorとcomponentDidCatchを宣言しているcomponentがErrorBoundaryとなる
getDrivedStateFromErrorはエラーを元にUIを変更するためのfunction(副作用のある処理は記述できない)
componentDidCatchはlogを記録するなどの副作用のある処理を記述する
React 16 から、どの error boundary でもエラーがキャッチされなかった場合に React コンポーネントツリー全体がunmountされるようになった
これはバグの発見が遅れたことによるUXの低下を防ぐため
これまではerrorをcatchしなければerrorが表示されなかった
エラーを適切にcatchしてユーザーの体験を損なわないようにするのが大切
code:ErrorBoundary.jsx
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
static getDrivedStateFromError(error) {
// throwされたerrorを受け取る
return {hasError: true}; // fallbackのためのstateを返す
}
componentDidCatch(error, errorInfo) {
/**
* error: throwされたエラー
* errorInfo: どのcomponentがエラーをthrowしたかの情報を含む
*/
logErrorToService(error, errorInfo);
}
render() {
if(this.state.hasError) {
return "エラーが発生しました";
}
return this.state.children;
}
}