programing

기능적 리액트 컴포넌트에서 오류 경계를 활용하는 방법은 무엇입니까?

newnotes 2023. 3. 16. 21:49
반응형

기능적 리액트 컴포넌트에서 오류 경계를 활용하는 방법은 무엇입니까?

클래스를 React에서 오류 경계로 만들있습니다.componentDidCatch.

기능성 컴포넌트를 클래스로 변환하지 않고 오차 경계로 만들 수 있는 깨끗한 접근법이 있는가?

아니면 코드 냄새인가요?

v16.2.0에서는 기능 컴포넌트를 에러 경계로 하는 방법은 없습니다.

React 문서에서는 이 점에 대해 명확하게 설명하지만 원하는 횟수만큼 재사용할 수 있습니다.

componentDidCatch()메서드는 JavaScript와 같이 동작합니다.catch {}블록이지만 컴포넌트용입니다.클래스 구성 요소만 오류 경계일 수 있습니다. 실제로 대부분의 경우 오류 경계 구성 요소를 한 번 선언하고 응용 프로그램 전체에서 사용해야 합니다.

또, 주의해 주세요.try/catch블록이 모든 경우에 효과가 있는 것은 아닙니다.
계층 깊숙이 있는 컴포넌트가 업데이트를 시도했다가 실패하면try/catch부모 중 한 명이 작동하지 않습니다. 아이와 함께 업데이트될 필요는 없기 때문입니다.

다음과 같은 기능 컴포넌트에 대해 존재하지 않는 기능으로 처리할 수 있는 구현이 있습니다.componentDidCatch그리고.deriveStateFromError.

작성자에 따르면 React.memo()를 기반으로 합니다.

제안된 솔루션은 새로운 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 (
      <div className="error-screen">
        <h2>An error has occured</h2>
        <h4>{error.message}</h4>
      </div>
    )
  } else {
    return <React.Fragment>{props.children}</React.Fragment>
  }
})

참조 및 API는 이쪽

이미 설명한 바와 같이 React 팀은 아직 에 상당하는 훅을 구현하지 않았으며 훅 구현에 대해 공개된 스케줄도 없습니다.

npm의 일부 서드파티 패키지에는 에러 경계 후크가 실장되어 있습니다.react-use-error-boundary를 퍼블리시하여 Preact에서 useErrorBoundary와 유사한 API를 재작성하려고 했습니다.

import { withErrorBoundary, useErrorBoundary } from "react-use-error-boundary";

const App = withErrorBoundary(({ children }) => {
  const [error, resetError] = useErrorBoundary(
    // You can optionally log the error to an error reporting service
    (error, errorInfo) => logErrorToMyService(error, errorInfo)
  );

  if (error) {
    return (
      <div>
        <p>{error.message}</p>
        <button onClick={resetError}>Try again</button>
      </div>
    );
  }

  return <div>{children}</div>;
});

Official React 팀은 기능 컴포넌트에 대한 오류 경계 지원을 제공하지 않았습니다.npm 패키지를 사용하여 기능 컴포넌트의 에러 경계를 설정할 수 있습니다.https://www.npmjs.com/package/react-error-boundary

내가 한 일은 커스텀을 만드는 것이다.class component그리고 나의 포장을 했다.functional/class컴포넌트가 필요한 곳에 내장되어 있습니다.커스텀 클래스 컴포넌트는 다음과 같습니다.

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

  componentDidCatch(error) {
    this.setState({error: `${error.name}: ${error.message}`});
  }

  render() {
    const {error} = this.state;
    if (error) {
      return (
        <div>{error}</div>
      );
    } else {
      return <>{this.props.children}</>;
    }
  }
}

그리고 이렇게 썼는데functional/class컴포넌트:

<ErrorBoundary key={uniqueKey}>
   <FuncationalOrChildComponent {...props} />
</ErrorBoundary>

PS: 항상 그렇듯이 키 속성은 매우 중요합니다.그것은 반드시 재렌더(render)를 하기 때문입니다.ErrorBoundary컴포넌트(동적 하위 요소인 경우)를 선택합니다.

언급URL : https://stackoverflow.com/questions/48482619/how-can-i-make-use-of-error-boundaries-in-functional-react-components

반응형