造一個 react-error-boundary 輪子

如下全部代碼都已整理到 Github:github.com/Haixiang612…html

參考的輪子:www.npmjs.com/package/rea…前端

發生甚麼事了

朋友們好啊,我是海怪,剛纔老闆對我說:海怪,發生甚麼事了,怎麼頁面白屏了?我說:怎麼回事?給我發了幾張截圖。我打開控制檯一看:react

哦!原來是昨天,有個後端年輕人,說要和我聯調接口,我說:能夠。而後,我說:小兄弟,你的數據儘可能按我須要的格式來:git

interface User {
    name: string;
    age: number;
}

interface GetUserListResponse {
    retcode: number;
    data: User[]
}
複製代碼

踏不服氣,他說你這個沒用,我說我這個有用,這是規範,傳統先後端聯調返回數據是要講規範的,對項目質量的提升能夠起到四兩撥千斤的做用。100多萬行代碼的系統,只要有了類型規範,都不會輕易崩潰。他說試試,我說行。github

我請求剛發出去,他的數據,啪!的一下就返回了!很快啊!!npm

{
    retcode: 0,
    data: [
        {name: '張三', age: 11},
        undefined,
        null
    ]
}
複製代碼

上來先是一個 retcode: 0,而後數組裏一個 User 對象,一個 undefined,一個 null,我所有用判斷 falsy 值防過去了啊:後端

if (!u) {
   return 0;
}

const trimName = u.name.trim();

return getScore(trimName);
複製代碼

防過去以後天然是正常處理業務邏輯和頁面展現。雖然沒有按照規範來,可是數組裏偶爾有個 falsy 值也還好,我把數組類型改爲 Array<string | null | undefined>,沒有和他說,同事之間,點到爲止。我笑一下提交測試了,發了正式環境,準備收工。而後,這時候,老闆忽然說線上白屏爆炸,我一看返回的數據:數組

{
    retcode: 0,
    data: [
        {name: '張三', age: 11},
        '找不到此用戶',
        '找不到此用戶',
        '找不到此用戶'
    ]
}
複製代碼

我大意了啊!沒有作類型判斷!立刻回滾。加了 if (typeof user === 'string') 的字符串類型判斷,準備再次發正式,可是我一想不對,難不成對每一個數據我都要像像佛同樣供着?瀏覽器

// 這就很離譜
try {
    const scores = users.map(u => {
        // 判空
        if (!u) {
            return;
        }

        // 判斷錯誤類型
        if (typeof u === 'string') {
            return;
        }

        // 判斷屬性是否存在
        if (!u.name) {
            return;
        }

        const trimName = u.name.trim(0);

        return getScore(trimName);
    })

    return scores;
} catch (e) {
    return null;
}
複製代碼

這明顯是後端沒有對錯誤進行特殊處理啊,可是做爲前端開發就算被後端百般蹂躪,頁面也不該該白屏,應該就那個組件報錯就行了。我定了定神,決定使出**「閃電五連鞭」**。服務器

34fe-kefmphe1371072.gif

相信你們對JS異常捕獲很熟悉了,try-catch 一包業務代碼就收工了。不過,在組件裏對異常捕獲,須要用到的是 React 提供的 Error Boundary 錯誤邊界特性,用 componentDidCatch 鉤子來對頁面異常進行捕獲,以致於不會將異常擴散到整個頁面,有效防止頁面白屏。

下面,我來展現一下怎麼打好這套**「閃電五連鞭」**。

第一鞭:抄

直接把官網例子抄下來,將 ErrorBoundary 組件輸出:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染可以顯示降級後的 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 你一樣能夠將錯誤日誌上報給服務器
    logger.error(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 你能夠自定義降級後的 UI 並渲染
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}
複製代碼

而後將業務組件包裹:

<ErrorBoundary> // 捕獲錯誤
  <UserList /> // 使勁報錯
</ErrorBoundary>
複製代碼

若是 UserList 裏報錯,ErrorBoundary 就會捕獲,而後在 getDerivedStateFromError 裏更新組件狀態,render 裏就會顯示 Something went wrong,不會渲染 this.props.children

總結: 1. 將 ErrorBoundary 包裹可能出錯的業務組件 2. 當業務組件報錯時,會調用 componentDidCatch 鉤子裏的邏輯,將 hasError 設置 true,直接展現

第二鞭:造個靈活的輪子

上面只是解決了燃眉之急,若是真要造一個好用的輪子,不該直接寫死 return <h1>Something went wrong</h1>,應該添加 props 來傳入報錯顯示內容(如下統稱爲 fallback):

// 出錯後顯示的元素類型
type FallbackElement = React.ReactElement<unknown, string | React.FC | typeof React.Component> | null;

// 出錯顯示組件的 props
export interface FallbackProps {
  error: Error;
}

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  fallback?: FallbackElement;
  onError?: (error: Error, info: string) => void;
}

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryState {
  error: Error | null; // 將 hasError 的 boolean 改成 Error 類型,提供更豐富的報錯信息
}

// 初始狀態
const initialState: ErrorBoundaryState = {
  error: null,
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  state = initialState;

  static getDerivedStateFromError(error: Error) {
    return {error};
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    if (this.props.onError) {
      this.props.onError(error, errorInfo.componentStack);
    }
  }

  render() {
    const {fallback} = this.props;
    const {error} = this.state;

    if (error !== null) {
      if (React.isValidElement(fallback)) {
        return fallback;
      }

      throw new Error('ErrorBoundary 組件須要傳入 fallback');
    }

    return this.props.children;
  }
}

export default ErrorBoundary
複製代碼

上面提供 onError 和 falback 兩個 props,前者爲出錯的回調,能夠作錯誤信息上報或者用戶提示,後者則傳入錯誤提示內容,像下面這樣:

const App = () => {
  return (
    <ErrorBoundary fallback={<div>出錯啦</div>} onError={logger.error('出錯啦')}> <UserList /> </ErrorBoundary>
  )
}
複製代碼

這已經讓 ErrorBoundary 變得稍微靈活一點了。可是有人就喜歡把 fallback 渲染函數、Fallback 組件做爲 props 傳入 ErrorBoundary,而不傳一段 ReactElement,因此爲了照顧更多人,將 fallback 進行擴展:

export declare function FallbackRender (props: FallbackProps): FallbackElement;

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  fallback?: FallbackElement; // 一段 ReactElement
  FallbackComponent?: React.ComponentType<FallbackProps>; // Fallback 組件
  fallbackRender?: typeof FallbackRender; // 渲染 fallback 元素的函數
  onError?: (error: Error, info: string) => void;
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  ...

  render() {
    const {fallback, FallbackComponent, fallbackRender} = this.props;
    const {error} = this.state;
    
    // 多種 fallback 的判斷
    if (error !== null) {
      const fallbackProps: FallbackProps = {
        error,
      }
      // 判斷 fallback 是否爲合法的 Element
      if (React.isValidElement(fallback)) {
        return fallback;
      }
      // 判斷 render 是否爲函數
      if (typeof fallbackRender === 'function') {
        return (fallbackRender as typeof FallbackRender)(fallbackProps);
      }
      // 判斷是否存在 FallbackComponent
      if (FallbackComponent) {
        return <FallbackComponent {...fallbackProps} />
      }

      throw new Error('ErrorBoundary 組件須要傳入 fallback, fallbackRender, FallbackComponent 其中一個');
    }

    return this.props.children;
  }
}
複製代碼

上面提供 3 種方式來傳入出錯提示組件: fallback(元素)、FallbackComponent(組件),fallbackRender(render 函數)。如今使用輪子就更靈活了:

const App = () => {
  const onError = () => logger.error('出錯啦')
  
  return (
    <div> <ErrorBoundary fallback={<div>出錯啦</div>} onError={onError}> <UserList /> </ErrorBoundary> <ErrorBoundary FallbackComponent={ErrorFallback} onError={onError}> <UserList /> </ErrorBoundary> <ErrorBoundary fallbackRender={(fallbackProps) => <ErrorFallback {...fallbackProps} />} onError={onError} > <UserList /> </ErrorBoundary> </div>
  )
}
複製代碼

總結一下這裏的改動: 1. 將原來的 hasError 轉爲 error,從 boolean 轉爲 Error 類型,有利於得到更多的錯誤信息,上報錯誤時頗有用 2. 添加 fallback, FallbackComponent, fallbackRender 3個 props,提供多種方法來傳入展現 fallback

第三鞭:添加劇置回調

有時候會遇到這種狀況:服務器忽然抽風了,50三、502了,前端獲取不到響應,這時候某個組件報錯了,可是過一會又正常了。比較好的方法是容許用戶點一下 fallback 裏的一個按鈕來從新加載出錯組件,不須要重刷頁面,這樣的操做下面稱爲**「重置」**。

同時,有些開發者也須要在重置裏添加本身邏輯,好比彈提示、日誌上報等。

圖解:

下面給出上面兩個需求的實現:

// 出錯後顯示的元素類型
type FallbackElement = React.ReactElement<unknown, string | React.FC | typeof React.Component> | null;

// 出錯顯示組件的 props
export interface FallbackProps {
  error: Error;
  resetErrorBoundary: () => void; // fallback 組件裏將該函數綁定到「重置」按鈕
}

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  ...
  onReset?: () => void; // 開發者自定義重置邏輯,如日誌上報、 toast 提示
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  ...
  // 重置該組件狀態,將 error 設置 null
  reset = () => {
    this.setState(initialState);
  }

  // 執行自定義重置邏輯,並重置組件狀態 
  resetErrorBoundary = () => {
    if (this.props.onReset) {
      this.props.onReset();
    }
    this.reset();
  }

  render() {
    const {fallback, FallbackComponent, fallbackRender} = this.props;
    const {error} = this.state;

    if (error !== null) {
      const fallbackProps: FallbackProps = {
        error,
        resetErrorBoundary: this.resetErrorBoundary,  // 將 resetErrorBoundary 傳入 fallback
      }

      if (React.isValidElement(fallback)) {
        return fallback;
      }
      if (typeof fallbackRender === 'function') {
        return (fallbackRender as typeof FallbackRender)(fallbackProps);
      }
      if (FallbackComponent) {
        return <FallbackComponent {...fallbackProps} />
      }

      throw new Error('ErrorBoundary 組件須要傳入 fallback, fallbackRender, FallbackComponent 其中一個');
    }

    return this.props.children;
  }
}
複製代碼

改寫以後,在業務代碼中添加劇置邏輯:

const App = () => {
  const onError = () => logger.error('出錯啦')
  const onReset = () => {
    console.log('已重置')
    message.info('剛剛出錯了,很差意思,如今已經重置好了,請找老闆錘這個開發')
  }
  // fallback 組件的渲染函數
  const renderFallback = (props: FallbackProps) => {
    return (
      <div> 出錯啦,你能夠<button onClick={props.resetErrorBoundary}>重置</button> </div>
    )
  }

  return (
    <div> <ErrorBoundary fallbackRender={renderFallback} onReset={onReset} onError={onError} > <UserList /> </ErrorBoundary> </div>
  )
}
複製代碼

上面例子中,在 onReset 裏自定義想要重試的邏輯,而後在 renderFallback 裏將 props.resetErrorBoudnary 綁定到重置便可,當點擊「重置」時,就會調用 onReset ,同時將 ErrorBoundary 組件狀態清空(將 error 設爲 null)。

總結: 1. 添加 onReset 來實現重置的邏輯 2. 在 fallback 組件裏找個按鈕綁定 props.resetErrorBoundary 來觸發重置邏輯

第四鞭:監聽渲染以重置

上面的重置邏輯簡單也很實用,可是有時也會有侷限性:觸發重置的動做只能在 fallback 裏面。假如個人重置按鈕不在 fallback 裏呢?或者 onReset 函數根本不在這個 App 組件下那怎麼辦呢?難道要將 onReset 像傳家寶一路傳到這個 App 再傳入 ErrorBoundary 裏?

這時,咱們就會想:能不能監聽狀態的更新,只要狀態更新就重置,反正就從新加載組件也沒什麼損失,這裏的狀態徹底用全局狀態管理,放到 Redux 中。

上面的思路聽起來不就和 useEffect 裏的依賴項 deps 數組同樣嘛,不妨在 props 提供一個 resetKeys 數組,若是這個數組裏的東西變了,ErrorBoundary 就重置,這樣一控制是否要重置就更靈活了。立刻動手實現一下:

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  ...
  resetKeys?: Array<unknown>;
}

// 檢查 resetKeys 是否有變化
const changedArray = (a: Array<unknown> = [], b: Array<unknown> = []) => {
  return a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]));
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  ...

  componentDidUpdate(prevProps: Readonly<React.PropsWithChildren<ErrorBoundaryProps>>) {
    const {error} = this.state;
    const {resetKeys, onResetKeysChange} = this.props;
    
    // 只要 resetKeys 有變化,直接 reset
    if (changedArray(prevProps.resetKeys, resetKeys)) {
      // 重置 ErrorBoundary 狀態,並調用 onReset 回調
      this.reset();
    }
  }

  render() {
    ...
  }
}
複製代碼

首先,在 componentDidupdate 裏去作 resetKeys 的監聽,只要組件有 render 就看看 resetKeys 裏面的元素是否改過了,改過了就會重置。

但這裏又會有一個問題:萬一 resetKeys 裏元素是個 Date 或者一個對象怎麼辦?因此,咱們還須要給開發者提供一種判斷 resetKeys 元素是否改變的方法,這裏就添加一個 onResetKeysChange 的 props 就行了:

// 本組件 ErrorBoundary 的 props
interface ErrorBoundaryProps {
  ...
  resetKeys?: Array<unknown>;
  onResetKeysChange?: ( prevResetKey: Array<unknown> | undefined, resetKeys: Array<unknown> | undefined, ) => void;
}

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  ...

  componentDidUpdate(prevProps: Readonly<React.PropsWithChildren<ErrorBoundaryProps>>) {
    const {resetKeys, onResetKeysChange} = this.props;

    if (changedArray(prevProps.resetKeys, resetKeys)) {
      if (onResetKeysChange) {
        onResetKeysChange(prevProps.resetKeys, resetKeys);
      }

      // 重置 ErrorBoundary 狀態,並調用 onReset 回調
      this.reset();
    }
  }

  render() {
    ...
  }
}
複製代碼

changedArray 斷定後,再次使用 props.onResetKeysChange 再次自定義判斷(若是有的話)resetKeys 裏的元素值是否有更新。

還有沒有問題呢?嗯,還有問題。這裏注意這裏的 componentDidUpdate 鉤子邏輯,假如某個 key 是觸發 error 的元兇,那麼就有可能觸發二次 error 的狀況:

  1. xxxKey 觸發了 error,組件報錯
  2. 組件報錯致使 resetKeys 裏的一些東西改了
  3. componentDidUpdate 發現 resetKeys 裏有東西更新了,不廢話,立刻重置
  4. 重置完了,顯示報錯的組件,由於 error 還存在(或者還未解決),報錯的組件又再次觸發了 error
  5. ...

因此要區分出來這一次究竟是由於 error 才 render 仍是普通組件的 render,並且還須要確保當前有錯誤才重置,都沒錯誤還重置個毛。具體實現思路如圖所示:

實現以下

class ErrorBoundary extends React.Component<React.PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
  state = initialState;
  // 是否已經因爲 error 而引起的 render/update
  updatedWithError = false;

  static getDerivedStateFromError(error: Error) {
    return {error};
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    if (this.props.onError) {
      this.props.onError(error, errorInfo.componentStack);
    }
  }
  
  componentDidUpdate(prevProps: Readonly<React.PropsWithChildren<ErrorBoundaryProps>>) {
    const {error} = this.state;
    const {resetKeys, onResetKeysChange} = this.props;
    
    // 已經存在錯誤,而且是第一次因爲 error 而引起的 render/update,那麼設置 flag=true,不會重置 
    if (error !== null && !this.updatedWithError) {
      this.updatedWithError = true;
      return;
    }

    // 已經存在錯誤,而且是普通的組件 render,則檢查 resetKeys 是否有改動,改了就重置
    if (error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
      if (onResetKeysChange) {
        onResetKeysChange(prevProps.resetKeys, resetKeys);
      }

      this.reset();
    }
  }

  reset = () => {
    this.updatedWithError = false;
    this.setState(initialState);
  }

  resetErrorBoundary = () => {
    if (this.props.onReset) {
      this.props.onReset();
    }
    this.reset();
  }

  render() {
    ...
  }
}
複製代碼

上面的改動有:

  1. updatedWithError 做爲 flag 判斷是否已經因爲 error 出現而引起的 render/update
  2. 若是當前沒有錯誤,不管如何都不會重置
  3. 每次更新:當前存在錯誤,且第一次因爲 error 出現而引起的 render/update,則設置 updatedWithError = true,不會重置狀態
  4. 每次更新:當前存在錯誤,且若是 updatedWithErrortrue 說明已經因爲 error 而更新過了,之後的更新只要 resetKeys 裏的東西改了,都會被重置

至此,咱們擁有了兩種能夠實現重置的方式了:

方法 觸發範圍 使用場景 思想負擔
手動調用 resetErrorBoundary 通常在 fallback 組件裏 用戶能夠在 fallback 裏手動點擊「重置」實現重置 最直接,思想負擔較輕
更新 resetKeys 哪裏都行,範圍更廣 用戶能夠在報錯組件外部重置、resetKeys 裏有報錯組件依賴的數據、渲染時自動重置 間接觸發,要思考哪些值放到 resetKeys 裏,思想負擔較重

總結這一鞭的改動: 1. 添加 resetKeysonResetKeysChange 兩個 props,爲開發者提供監聽值變化而自動重置的功能 2. 在 componentDidUpdate 裏,只要不是因爲 error 引起的組件渲染或更新,並且 resetKeys 有變化了,那麼直接重置組件狀態來達到自動重置

這裏自動重置還有一個好處:假如是因爲網絡波動引起的異常,那頁面固然會顯示 fallback 了,若是用上面直接調用 props.resetErrorBoundary 方法來重置,只要用戶不點「重置」按鈕,那塊地方永遠不會被重置。又因爲是由於網絡波動引起的異常,有可能就那0.001 秒有問題,別的時間又好了,因此若是咱們將一些變化頻繁的值放到 resetKeys 裏就很容易自動觸發重置。例如,報錯後,其它地方的值變了從而更改了 resetKeys 的元素值就會觸發自動重置。對於用戶來講,最多隻會看到一閃而過的 fallback,而後那塊地方又正常了。這樣一來,用戶也不須要親自觸發重置了。

第五鞭:輸出輪子

上面四鞭裏,到最後都是 export default ErrorBoundary 將組件輸出,若是代理裏不少個地方都要 catch error,就有這樣很囉嗦的代碼:

<div>
  <ErrorBoundary>
    <AAA/>
  </ErrorBoundary>
  <ErrorBoundary>
    <BBB/>
  </ErrorBoundary>
  <ErrorBoundary>
    <CCC/>
  </ErrorBoundary>
  <ErrorBoundary>
    <DDD/>
  </ErrorBoundary>
</div>
複製代碼

要處理這樣囉嗦的包裹,能夠借鑑 React Router 的 withRouter 函數,咱們也能夠輸出一個高階函數 withErrorBoundary

/** * with 寫法 * @param Component 業務組件 * @param errorBoundaryProps error boundary 的 props */
function withErrorBoundary<P> (Component: React.ComponentType<P>, errorBoundaryProps: ErrorBoundaryProps): React.ComponentType<P> {
  const Wrapped: React.ComponentType<P> = props => {
    return (
      <ErrorBoundary {...errorBoundaryProps}> <Component {...props}/> </ErrorBoundary>
    )
  }

  // DevTools 顯示的組件名
  const name = Component.displayName ||Component.name || 'Unknown';
  Wrapped.displayName = `withErrorBoundary(${name})`;

  return Wrapped;
}
複製代碼

使用的時候就更簡潔了一些了:

// 業務子組件
const User = () => {
  return <div>User</div>
}

// 在業務組件加一層 ErrorBoundary
const UserWithErrorBoundary = withErrorBoundary(User, {
  onError: () => logger.error('出錯啦'),
  onReset: () => console.log('已重置')
})

// 業務父組件
const App = () => {
  return (
    <div> <UserWithErrorBoundary/> </div>
  )
}
複製代碼

其實 withXXX 這種寫法還能夠寫成裝飾器,將 @withXXX 放到 class component 上也很方便,可是對於 functional component 就放不了了,有點受限,這裏不展開了。

還有沒有更好的設計呢?咱們觀察到只有一些比較「嚴重的異常」瀏覽器纔會報錯,好比開頭提到的 TypeError: xxx is not a function。JS 是個動態類型語言,在瀏覽器裏你能夠:NaN + 1,能夠 NaN.toString(),能夠 '1' + 1 都不報任何錯誤。其實官網也說了,對於一些錯誤 componenDidCatch 是不能自動捕獲的:

不過,這些錯誤在代碼裏開發者實際上是知道的呀。既然開發者們有辦法拿到這些錯誤,那把錯誤直接拋出就可讓 ErrorBoundary catch 到了:

  1. 有錯誤的時候,開發者本身調用 handleError(error) 將錯誤傳入函數中
  2. handleError 將錯誤 throw new Error(error)
  3. ErrorBoundary 發現有上面拋出的 Error,調用 componentDidCatch 處理錯誤
  4. ...

我來提供一種使用 React Hook 的實現方式:

/** * 自定義錯誤的 handler * @param givenError */
function useErrorHandler<P=Error>( givenError?: P | null | undefined, ): React.Dispatch<React.SetStateAction<P | null>> {
  const [error, setError] = React.useState<P | null>(null);
  if (givenError) throw givenError; // 初始有錯誤時,直接拋出
  if (error) throw error; // 後來再有錯誤,也直接拋出
  return setError; // 返回開發者可手動設置錯誤的鉤子
}
複製代碼

使用上面的 hook,對於一些須要本身處理的錯誤,能夠有兩種處理方法:

  1. const handleError = useErrorHandler(),而後 handleError(yourError)
  2. useErrorHandler(otherHookError),若是別的 hooks 裏有 export error,徹底能夠直接將這個 error 傳入 useErrorHandler,直接處理

好比:

function Greeting() {
  const [greeting, setGreeting] = React.useState(null)
  const handleError = useErrorHandler()

  function handleSubmit(event) {
    event.preventDefault()
    const name = event.target.elements.name.value
    fetchGreeting(name).then(
      newGreeting => setGreeting(newGreeting),
      handleError, // 開發者本身處理錯誤,將錯誤拋出
    )
  }

  return greeting ? (
    <div>{greeting}</div>
  ) : (
    <form onSubmit={handleSubmit}> <label>Name</label> <input id="name" /> <button type="submit">get a greeting</button> </form>
  )
}
// 用 ErrorBoundary 包裹,處理手動拋出的錯誤
export default withErrorBoundary(Greeting)
複製代碼

或者:

function Greeting() {
  const [name, setName] = React.useState('')
  const {greeting, error} = useGreeting(name)

  // 開發者本身處理錯誤,將錯誤拋出
  useErrorHandler(error)

  function handleSubmit(event) {
    event.preventDefault()
    const name = event.target.elements.name.value
    setName(name)
  }

  return greeting ? (
    <div>{greeting}</div>
  ) : (
    <form onSubmit={handleSubmit}> <label>Name</label> <input id="name" /> <button type="submit">get a greeting</button> </form>
  )
}

// 用 ErrorBoundary 包裹,處理手動拋出的錯誤
export default withErrorBoundary(Greeting)
複製代碼

總結: 1. 提供 withErrorBoundary 方法來包裹業務組件實現異常捕獲 2. 提供 useErrorHandler hook 讓開發者本身處理/拋出錯誤

「閃電五連鞭」總結

再次總結一下「抓錯五連鞭」的要點:

  1. 造一個 ErrorBoundary 輪子
  2. componentDidCatch 捕獲頁面報錯,getDerivedStateFromError 更新 ErrorBoundary 的 state,並獲取具體 error
  3. 提供多種展現錯誤內容入口:fallback, FallbackComponent, fallbackRender
  4. 重置鉤子:提供 onReset, resetErrorBoundary 的傳值和調用,以實現重置
  5. 重置監聽數組:監聽 resetKeys 的變化來重置。對於擁有複雜元素的 resetKeys 數組提供 onResetKeysChange 讓開發者自行判斷。在 componentDidUpdate 裏監聽每次渲染時 resetKeys 變化,並設置 updatedWithError 做爲 flag 判斷是否因爲 error 引起的渲染,對於普通渲染,只要 resetKeys 變化,直接重置
  6. 提供 ErrorBoundary 的2種使用方法:嵌套業務組件,將業務組件傳入withErrorBoundary 高階函數。提供 useErrorBoundary 鉤子給開發者本身拋出 ErrorBoundary 不能自動捕獲的錯誤

耗子尾汁,好好反思

打完了這一套「五連鞭」,再次發佈上線,一切OK。

而後我找到這位後端,跟他說了線上事故。當時他就流眼淚了,捂着臉,兩分多鐘之後,就行了。

我說:小夥子,你不講碼德你不懂。他說:對不起,我不懂規矩。後來他說他寫了好幾年動態語言,啊,看來是有 bear 來。這個年輕人不講碼德。來!騙!來!偷襲我一個24歲小前端,這好嗎?這很差,我勸,這位後端,耗子尾汁,好好反思,之後不要搞這樣的聰明,小聰明。程序猿要以和爲貴,要講碼德,不要搞窩裏鬥。

謝謝朋友們。

(故事純屬虛構,若有雷同,請自我反省或者一鍵三連)

相關文章
相關標籤/搜索