componentDidCatch와 동등한 리액트 훅?
리액트 앱에서 오류 경계로 기능하는 간단한 컴포넌트가 있으며, 이 컴포넌트는 에러를 로깅 서비스로 전달합니다.
다음과 같습니다.
export class CatchError extends React.PureComponent {
state = {
hasError: false
}
componentDidCatch(error, info) {
this.props.log({ error, info })
this.setState({ hasError: true })
}
render() {
const child = typeof this.props.children === "function"
? this.props.children({ error: hasError })
: children
return React.cloneElement(child, { error: this.state.hasError })
}
}
리액트 훅은 다음과 같습니까?componentDidCatch이 컴포넌트를 클래스가 아닌 기능으로 만들 수 있을까요?
그래서 다음과 같이 보일 수식어는 다음과 같습니다.
export function CatchError({ children, log }) {
const [hasError, setHasError] = useState(false)
const caught = useDidCatch()
useEffect(() => {
const [error, info] = caught
log({ error, info })
setHasError(true)
}, [caught])
const child = typeof children === "function"
? children({ error: hasError })
: children
return React.cloneElement(child, { error: hasError })
}
다음과 같은 리액트 훅은 없습니다.componentDidCatch.
하지만 리액트 팀은 곧 하나를 추가할 계획이다.
React 문서 상태:
일반적이지 않은 getSnapshotBeforeUpdate 및 componentDidCatch 라이프사이클에 해당하는 Hook은 아직 없지만 조만간 추가할 예정입니다.
상세내용 : https://reactjs.org/docs/hooks-faq.html#do-hooks-cover-all-use-cases-for-classes
반응에는 Error Boundaries(componentDidCatch)에 대한 공식 후크는 없지만 try...catch를 사용하여 다음과 같은 컴포넌트 오류를 캐치할 수 있습니다.
function myComponent(...) {
// Initialize state variables.
// Initialize context variables.
// Initialize custom hooks.
// ...
try {
// Define internal functions.
// Define internal variables.
return (
<SomeThing />
)
} catch (error) {
// Catch internal functions, variables and return (jsx) errors.
// You can also create a lib to log the error to an error reporting service
// and use it here.
}
}
그try...catch여기서 block은 오류 경계입니다.
제한사항: 다음과 같은 후크를 사용하는 경우useEffect그리고 당신은 약간의internal functionsuseEffect hook(왜?) 위에 함수를 정의해야 하고 useEffect(왜?)를 조건부로 사용하면 안 되기 때문에 내부 함수를 try...catch(에러 경계) 블록에 넣을 수 없습니다.
이미 설명한 바와 같이 React 팀은 아직 훅에 상당하는 훅을 구현하지 않았으며 훅 구현에 대해 공개된 스케줄도 없습니다.
npm의 일부 서드파티 패키지에는 에러 경계 후크가 실장되어 있습니다.이것이 가장 인기 있는 npm 패키지입니다.또는 react-use-error-boundary를 퍼블리시하여 Preact에서 useErrorBoundary와 유사한 API를 재작성하려고 했습니다.
언급URL : https://stackoverflow.com/questions/59932119/react-hooks-equivalent-of-componentdidcatch
'programing' 카테고리의 다른 글
| Woocommerce 제품 변동 드롭다운에 변동 재고 상태를 추가하는 방법 (0) | 2023.03.05 |
|---|---|
| react 라우터 v^4.0.0 Uncaughed TypeError: 정의되지 않은 속성 '위치'를 읽을 수 없습니다. (0) | 2023.03.05 |
| Configuration Properties를 사용한 일반적인 맵 채우기 (0) | 2023.03.05 |
| PyMongo 3이 Server Selection을 제공하는 이유TimeoutError? (0) | 2023.03.05 |
| Ajax의 유형과 메서드 간 차이는 무엇입니까? (0) | 2023.03.05 |