首頁  >  文章  >  web前端  >  掌握 React 中的錯誤邊界:有效錯誤處理指南

掌握 React 中的錯誤邊界:有效錯誤處理指南

WBOY
WBOY原創
2024-07-20 00:55:30587瀏覽

Mastering Error Boundaries in React: A Guide to Effective Error Handling

什麼是誤差邊界?

建立應用程式時,錯誤是不可避免的。它們可能來自 API、UI 或其他幾個地方。

儘管有這些錯誤,但優雅地處理這些錯誤並保持良好的使用者體驗非常重要。

錯誤邊界是 React 中錯誤處理的一種方式。


錯誤邊界有什麼幫助?

為了理解這一點,我們先了解引入誤差邊界之前的情況。

在錯誤邊界之前,元件內部發生的錯誤最終會傳播並破壞 UI 或呈現白屏。

這導致了非常糟糕的使用者體驗。

錯誤邊界幫助我們處理此類錯誤並顯示後備 UI,而不是破壞 UI 或顯示白屏。


如何使用誤差邊界?

React v16 正式引進了Error Boundary。

它是一個基於類別的元件,可用於包裝您的應用程式。

它接受要顯示的後備 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 的錯誤邊界有什麼問題?

它無法捕捉

中發生的錯誤
  • 事件處理程序(這些錯誤需要使用 try-catch 區塊處理)
  • 非同步程式碼(API、setTimeout、requestAnimationFrame 等)
  • 服務端渲染
  • 錯誤邊界本身發生的錯誤
  • 它不適用於功能組件。儘管我們可以通過一些程式碼更改來使其工作。
  • 裡面不能使用掛鉤。

解決方法是什麼?

有一個名為react-error-boundary的npm包,它是傳統錯誤邊界元件之上的包裝器。

使用這個包,我們能夠克服傳統錯誤邊界組件中面臨的所有問題。


如何使用?

您可以使用 .

包裝整個應用程序,也可以使用 .

包裝單個組件

實施的粒度由您決定。


讓我們來了解如何使用它。

import React from 'react';
import { ErrorBoundary } from "react-error-boundary";

const App = () => {
return <ErrorBoundary fallback={<div>Something went wrong</div>}>
/* rest of your component */
</ErrorBoundary>
}

這是使用 ErrorBoundary 的最簡單的範例。這個庫還有更多內容。

了解反應錯誤邊界 API

讓我們試著了解不同場景下的 API。

1。我想針對應用程式中的錯誤顯示通用後備 UI

 import React from 'react';
 import { ErrorBoundary } from "react-error-boundary";

 const App = () => {
 return <ErrorBoundary fallback={<div>Something went wrong</div>}>
 /* rest of your component */
 </ErrorBoundary>
 }

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 (
     <div role="alert">
       <p>Something went wrong:</p>
       <pre style={{ color: "red" }}>{error.message}
); } const App = () => { return { // 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 (
     <div role="alert">
       <p>Something went wrong:</p>
       <pre style={{ color: "red" }}>{error.message}
); } const App = () => { return { // 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 (
     <div role="alert">
       <p>Something went wrong:</p>
       <pre style={{ color: "red" }}>{error.message}
); } // You can use fallback / fallbackRender / FallbackComponent anything const App = () => { return { // 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 <Whatever UI you want to render/>
 }


一些問題

ErrorBoundary 是一個客戶端元件。您只能將可序列化的屬性傳遞給它,或在具有「使用客戶端」的檔案中使用它;指令。

1。什麼是可序列化的 prop?

Serilzable prop 表示它可以轉換為位元組流,這樣位元組流就可以轉換回原始 prop。

在 Javascript 中執行此操作的常見方法是 JSON.stringify() 和 JSON.parse()。

2。如何使用「使用客戶端」;指令?


只需在文件上方提及即可

"use client";


您也可以使用更多的變體。但這篇文章足以讓您入門。

在這裡查看他們的完整文件。

如果您覺得有幫助,請在評論中告訴我。

編碼快樂!

以上是掌握 React 中的錯誤邊界:有效錯誤處理指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript json npm if for while try catch Error using class Event Generic this display ux ui
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:Flutter 與 React Native下一篇:Flutter 與 React Native

相關文章

看更多