HOC 与错误边界
约 378 字大约 1 分钟
布欧-Lewyon
2026-05-15
高阶组件(HOC)
HOC 是"接受组件并返回新组件"的函数。
// 加载中 HOC
function withLoading<P>(Component: React.ComponentType<P>) {
return function WithLoading(props: P & { loading: boolean }) {
const { loading, ...rest } = props
if (loading) return <div className="spinner" />
return <Component {...rest as P} />
}
}
interface UserProfileProps { user: { name: string } }
function UserProfile({ user }: UserProfileProps) {
return <div>{user.name}</div>
}
const UserProfileWithLoading = withLoading(UserProfile)
// 使用
<UserProfileWithLoading loading={true} user={null} />
<UserProfileWithLoading loading={false} user={{ name: 'Alice' }} />withAuth
function withAuth<P extends object>(Component: React.ComponentType<P>) {
return function WithAuth(props: P) {
const user = useCurrentUser()
if (!user) {
return <Navigate to="/login" replace />
}
return <Component {...props} user={user} />
}
}
const ProtectedDashboard = withAuth(Dashboard)错误边界
interface ErrorBoundaryProps {
children: React.ReactNode
fallback?: React.ReactNode
}
interface ErrorBoundaryState {
hasError: boolean
error: Error | null
}
class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props)
this.state = { hasError: false, error: null }
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error }
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
console.error('Error caught:', error, info)
// 上报错误日志
}
render() {
if (this.state.hasError) {
return this.props.fallback || (
<div className="error-boundary">
<h2>出错了</h2>
<p>{this.state.error?.message}</p>
<button onClick={() => this.setState({ hasError: false })}>
重试
</button>
</div>
)
}
return this.props.children
}
}
// 使用
function App() {
return (
<ErrorBoundary fallback={<p>页面崩溃了</p>}>
<Dashboard />
</ErrorBoundary>
)
}useErrorBoundary 自定义 Hook 封装
function useThrowError() {
const [, setState] = useState()
return useCallback((error: Error) => {
setState(() => { throw error })
}, [])
}小结
- HOC
withXxx(Component)注入通用逻辑,现代 React 中优先用 Hook。 - 错误边界目前只能由 class 组件实现,捕获子组件渲染错误。
componentDidCatch上报错误日志。- 错误边界不能捕获自身错误、异步错误、事件处理错误。
