我正在学习 React,当 API 服务器不可用时,无法获取错误边界来捕获子组件中 axios http 请求引发的网络连接错误。
我可以看到错误记录在子组件的 catch 处理程序中,但是 ErrorBoundary 组件没有捕获 throw 语句。
任何想法如何让错误边界捕获抛出的错误组件已挂载生命周期方法?
父级 - App.tsx
export class App extends React.Component<AppProps, {}> {
public render(): JSX.Element {
return (
<div>
<ErrorBoundary>
<AppBar color="primary" position="static">
<Toolbar>
<TypoGraphy variant="h6" color="inherit">
Course App
</TypoGraphy>
<NavBar />
</Toolbar>
</AppBar>
<CourseList />
</ErrorBoundary>
</div>
);
}
}
子级 - CourseList.tsx
componentDidMount(): void {
console.log('CourseList::componentDidMount');
const dataSource: RestDataCourse = new RestDataCourse();
dataSource
.getCourses()
.then(courseList => {
this.setState({ courses: courseList });
})
.catch(error => {
console.error(`Error retrieving courses => ${JSON.stringify(error)}`);
throw error;
});
}
错误边界
import * as React from 'react';
interface ErrorBoundaryProps {
hasError: boolean;
error: Error;
info: React.ErrorInfo;
}
export default class ErrorBoundary extends React.Component<
{},
ErrorBoundaryProps
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: undefined, info: undefined };
}
componentDidCatch(error: any, info: any): void {
console.log('ErrorBoundary has encountered an error');
this.setState({ hasError: true, error: error, info: info });
}
render(): {} {
if (this.state.hasError) {
return (
<div id="errorModal" className="modal">
<div className="modal-content">
<span className="close">×</span>
<h2>Application Crash</h2>
<p>Error encountered in application.</p>
{this.state.error}
</div>
</div>
);
}
// Render children if no error
return this.props.children;
}
}