什么时候应该使用类组件而不是函数组件?
有一个情况下,你可能还需要使用类组件,React组件错误捕获。
React组件错误捕获怎么做?
封装
import React, { Component } from "react";
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// 更新状态以显示降级 UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// 记录错误信息(例如发送到日志服务)
console.error("Error caught by ErrorBoundary:", error, errorInfo);
}
render() {
if (this.state.hasError) {
// 降级 UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
使用
function App() {
return (
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
);
}
注意事项:
-
ErrorBoundaries只能监听组件渲染报错 -
生成环境才生效, 开发环境直接抛出错误
-
无法捕获以下错误:
- 不会监听dom事件报错
- 例如
click事件中的错误 - 可以用
window.onerror监听 - 或者
try catch监听
- 例如
- 异步代码
- 如
setTimeout或Promise中的错误。 - 异步报错使用
window.onerror监听
- 如
- 服务端渲染中的错误。
- 错误边界组件自身的错误。
- 不会监听dom事件报错