これは
Reactのガイドを読んでいく記事です。
ガイドのリンク
React.Component
まれに使われるライフサイクルメソッド
componentDidCatch()
エラーがスローされた時に呼び出される。
getDerivedStateFromError()
とは違ってエラーを受け取って、
エラーをスローしたのがどのコンポーネントか判別できるような情報を受け取る。
ロギングのエラーとかに使用するのはいい使い方らしい。
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // 次のレンダーでフォールバック UI が表示されるように state を更新します return { hasError: true }; } componentDidCatch(error, info) { // Example "componentStack": // in ComponentThatThrows (created by App) // in ErrorBoundary (created by App) // in div (created by App) // in App logComponentStackToMyService(info.componentStack); } render() { if (this.state.hasError) { // 任意のフォールバック UI をレンダーできます return <h1>Something went wrong.</h1>; } return this.props.children; } }
今日はここまで。