【发布时间】:2018-12-07 17:15:21
【问题描述】:
在我的 componentDidCatch() 方法中捕获错误,并呈现自定义错误 UI。
什么是摆脱错误并且不让用户强制更新页面的巧妙方法?
import * as React from "react";
interface ErrorBoundaryState {
hasError: boolean;
errorInfo: React.ErrorInfo;
}
export class ErrorBoundary extends React.Component<{}, ErrorBoundaryState> {
constructor(props: any) {
super(props);
this.state = {
hasError: false,
errorInfo: undefined,
};
}
public componentDidCatch(error: Error, info: React.ErrorInfo) {
this.setState({
hasError: true,
errorInfo: info
});
console.error(error, info);
}
public render() {
if (this.state.hasError) {
return (
<h2>Something went wrong, please try again later.</h2>
);
}
return this.props.children;
}
}
当 hasError 设置为 true 时,它会停留在那里。将它设置为 false 并再次向孩子们展示的好地方在哪里?
【问题讨论】:
标签: javascript reactjs error-handling redux react-16