アプリケーションを構築する際、エラーは避けられません。これらは API、UI、またはその他の場所から取得される可能性があります。
これらのエラーを適切に処理し、これらのエラーにもかかわらず良好な UX を維持することが非常に重要です。
エラー境界は、React でのエラー処理方法の 1 つです。
これを理解するために、エラー境界が導入される前の状況を理解しましょう。
エラー境界の前では、コンポーネント内で発生したエラーが最終的に伝播し、UI が壊れたり、白い画面が表示されたりしました。
これにより、非常に悪い UX が発生しました。
エラー境界は、UI を壊したり白い画面が表示されたりするのではなく、このようなエラーを処理し、フォールバック UI を表示するのに役立ちます。
React v16 ではエラー境界が正式に導入されました。
これは、アプリケーションをラップするために使用できるクラスベースのコンポーネントです。
アプリケーションにエラーが発生した場合や、そうでない場合に表示されるフォールバック UI を受け入れます。単に子コンポーネントをレンダリングして、アプリケーションの通常のフローを再開します。
これが React ドキュメントで推奨されている使用方法です。
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. 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 logErrorToMyService(error, info.componentStack); } render() { if (this.state.hasError) { // You can render any custom fallback UI return this.props.fallback; } return this.props.children; } }
react-error-boundary という npm パッケージがあり、これは従来のエラー境界コンポーネントの上にあるラッパーです。
このパッケージを使用すると、従来のエラー境界コンポーネントで直面するすべての問題を克服できます。
アプリケーション全体を .
でラップすることも、個々のコンポーネントをラップすることもできます。実装の粒度はあなた次第です。
使い方を理解しましょう。
import React from 'react'; import { ErrorBoundary } from "react-error-boundary"; const App = () => { returnSomething went wrong}> /* rest of your component */ }
これは、ErrorBoundary を使用する最も簡単な例です。このライブラリにはさらに多くの機能があります。
さまざまなシナリオで API を理解してみましょう。
1.アプリケーションのエラーに対する汎用フォールバック UI を表示したい
import React from 'react'; import { ErrorBoundary } from "react-error-boundary"; const App = () => { returnSomething went wrong}> /* rest of your component */ }
2.フォールバックコンポーネント
で特定のエラーの詳細を表示したい
import React from 'react'; import { ErrorBoundary } from "react-error-boundary"; function fallbackRender({ error, resetErrorBoundary }) { // Call resetErrorBoundary() to reset the error boundary and retry the render. return (); } const App = () => { { // エラーが再度発生しないようにアプリの状態をリセットします }} > /* コンポーネントの残りの部分 */ エラー境界> }); } const App = () => { returnSomething went wrong:
{error.message}{ // Reset the state of your app so the error doesn't happen again }} > /* rest of your component */ }
fallback または fallbackRender の代わりに、React コンポーネントを使用することもできます。
import React from 'react'; import { ErrorBoundary } from "react-error-boundary"; const Fallback = ({ error, resetErrorBoundary }) => { // Call resetErrorBoundary() to reset the error boundary and retry the render. return (); } const App = () => { { // エラーが再度発生しないようにアプリの状態をリセットします }} > /* コンポーネントの残りの部分 */ エラー境界> }); } const App = () => { returnSomething went wrong:
{error.message}{ // Reset the state of your app so the error doesn't happen again }} > /* rest of your component */ }
3.エラーをログに記録したい
import React from 'react'; import { ErrorBoundary } from "react-error-boundary"; const logError = (error: Error, info: { componentStack: string }) => { // Do something with the error, e.g. log to an external API }; const Fallback = ({ error, resetErrorBoundary }) => { // Call resetErrorBoundary() to reset the error boundary and retry the render. return (); } // fallback / fallbackRender / FallbackComponent なら何でも使えます const App = () => { { // エラーが再度発生しないようにアプリの状態をリセットします }} > /* コンポーネントの残りの部分 */ エラー境界> }); } // You can use fallback / fallbackRender / FallbackComponent anything const App = () => { returnSomething went wrong:
{error.message}{ // Reset the state of your app so the error doesn't happen again }} > /* rest of your component */ }
4.イベントハンドラーと非同期コードのエラーをキャッチしたい
import { useErrorBoundary } from "react-error-boundary"; function Example() { const { showBoundary } = useErrorBoundary(); const getGreeting = async(name) => { try { const response = await fetchGreeting(name); // rest of your code } catch(error){ // Show error boundary showBoundary(error); } } useEffect(() => { getGreeting() }); return}
ErrorBoundary はクライアント コンポーネントです。シリアル化可能な props を渡すことも、「use client」を持つファイルで使用することもできます。指令。
1.シリアル化可能なプロパティとは何ですか?
Serilzable prop は、バイト ストリームを元の prop に変換できるような方法でバイト ストリームに変換できることを意味します。
JavaScript でこれを行う一般的な方法は、JSON.stringify() と JSON.parse() です。
2. 「クライアントを使用する」の使い方;指令?
ファイルの先頭に記載するだけです
"use client";
さらにいくつかのバリエーションを使用できます。ただし、この記事は始めるのに十分です。
ここで完全なドキュメントをチェックしてください。
役に立ったと思われた場合は、コメントでお知らせください。
コーディングを楽しんでください!
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3