How can I make use of Error boundaries in functional React components?

后端 未结 2 681
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 23:07

I can make a class an error boundary in React by implementing componentDidCatch.

Is there a clean approach to making a functional component into an error bo

2条回答
  •  有刺的猬
    2021-02-04 23:46

    There is an implementation that can handle with non-existent functionalities for a functional component such as componentDidCatch and deriveStateFromError.

    According to the author, it is based on React.memo().

    The proposed solution is greatly inspired by the new React.memo() API.

    import Catch from "./functional-error-boundary"
    
    type Props = {
      children: React.ReactNode
    }
    
    const MyErrorBoundary = Catch(function MyErrorBoundary(props: Props, error?: Error) {
      if (error) {
        return (
          

    An error has occured

    {error.message}

    ) } else { return {props.children} } })

    reference and API here

提交回复
热议问题