M3g*_*ana 12 javascript reactjs react-hooks react-error-boundary
这是我的错误边界文件 -
class ErrorHandling extends Component {
state = { hasError: false }
componentDidCatch() {
this.setState({ hasError: true })
}
render() {
// debugger
if (this.state.hasError) {
return <div>Error in Component</div>
}
return this.props.children
}
}
Run Code Online (Sandbox Code Playgroud)
另一个文件是-
import React, { Component } from 'react';
// Intentionally I have added syntax error below 'd'
function Intermediate(props) {
return <h1>hi</h1>;d
}
export default Intermediate
Run Code Online (Sandbox Code Playgroud)
在我的 App.js 中
<ErrorHandling>
<Intermediate />
</ErrorHandling>
Run Code Online (Sandbox Code Playgroud)
它导致应用程序在没有捕获错误的情况下中断。这是在浏览器屏幕上看到的错误
更详细的版本在这里 - https://codepen.io/meghana1991/pen/abojydj?editors=0010
当我在本地使用与上面列出的多个文件相同的代码时,它不起作用
Den*_*ash 23
您无法捕获编译时错误,错误边界用于 UI 中的运行时错误。
请参阅编译时与运行时错误。
此外,为了在回退 UI 上添加额外的渲染,您必须使用getDerivedStateFromError:
class ErrorBoundary extends React.Component {
state = {
hasError: false,
error: { message: '', stack: '' },
info: { componentStack: '' }
};
static getDerivedStateFromError = error => {
return { hasError: true };
};
componentDidCatch = (error, info) => {
this.setState({ error, info });
};
render() {
const { hasError, error, info } = this.state;
const { children } = this.props;
return hasError ? <ErrorComponent/> : children;
}
}
Run Code Online (Sandbox Code Playgroud)
为了检查您的ErrorBoundary,从组件树中的可访问部分抛出错误,该部分不是:
const ButtonComponent = () => {
throw Error("error!");
return <></>;
};
Run Code Online (Sandbox Code Playgroud)
注意:在开发环境中,除非您将其关闭或使用 X 按钮关闭它,否则您将始终看到错误覆盖。
完整示例:
const ErrorComponent = () => {
return <h1>Something went wrong</h1>;
};
class ErrorBoundary extends React.Component {
state = {
hasError: false,
error: { message: "", stack: "" },
info: { componentStack: "" }
};
static getDerivedStateFromError = error => {
return { hasError: true };
};
componentDidCatch = (error, info) => {
this.setState({ error, info });
};
render() {
const { hasError, error, info } = this.state;
console.log(error, info);
const { children } = this.props;
return hasError ? <ErrorComponent /> : children;
}
}
const ButtonComponent = () => {
throw Error("error!");
return <></>;
};
const App = () => {
return (
<ErrorBoundary>
<ButtonComponent />
</ErrorBoundary>
);
};
Run Code Online (Sandbox Code Playgroud)