- React 提供了一个生命周期方法 componentDidCatch,可以帮助我们捕获并处理组件中的错误。
- 我们可以使用 try…catch 语句来捕获渲染组件时出现的错误,并通过componentDidCatch 方法将错误信息存储到组件的状态中。然后通过控制组件的渲染来切换到其他组件。
import React, { ReactNode } from "react";
interface ErrorBoundaryState {
hasError: boolean;
}
interface ErrorBoundaryProps {
children: ReactNode;
}
export class ErrorBoundary extends React.Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error: any) {
return { hasError: true };
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>报错啦.</h1>;
}
return this.props.children;
}
}
/**
* 处理错误
* @param error
* @param errorInfo
*/
function logErrorToMyService(error: Error, errorInfo: React.ErrorInfo) {
//.........
}
使用这个错误边界,只需要将需要捕获的组件包裹在它的内部即可。 如果在 MyComponent 渲染过程中发生了错误,错误将被
ErrorBoundary 捕获,并切换到降级 UI,而不是导致整个应用程序崩溃。