我创建了我的反应应用程序vite
在那里我有我的自定义反应错误边界组件从组件包装,事情是它无法捕获错误。我调试我的错误组件,但它无法接收任何值getDerivedStateFromError
not componentDidCatch
这是我的错误边界代码:
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { Component } from 'react';
interface IState {
hasError: boolean;
eventId?: string;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface IProps {
children: any;
}
export default class ErrorBoundary extends Component<IProps, IState> {
constructor(props: Readonly<{}>) {
super(props);
this.state = { eventId: '', hasError: false };
}
static getDerivedStateFromError(error: any) {
console.log('here get Derived');
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error: any, errorInfo: any) {
console.log('My errors', error);
}
render() {
// const { children } = this.props;
console.log('errors');
if (this.state.hasError) {
console.log('errors found', this.state.hasError);
return (
<button
onClick={() =>
console.log("Error Found)
}
>
Report feedback
</button>
);
}
return this.props.children;
}
}
和我的 app.js 代码:
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<ErrorBoundary>
<button
onClick={() => {
throw new Error('Im new Error');
}}
>
Click Me
</button>
</ErrorBoundary>
</header>
</div>
);
}
export default App;
有人知道是什么问题吗?
错误边界不会捕获以下错误:
- 事件处理程序
- 异步代码(例如 setTimeout 或 requestAnimationFrame
回调)
- 服务端渲染
- 错误边界本身抛出的错误
(而不是它的孩子)
https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries
要模拟错误,您需要创建一个组件,使其成为 ErrorBoundary 类的子组件,然后单击按钮 2 次
function Button() {
const [count, setCount] = useState(0);
const onClick = () => {
setCount(count + 1);
};
useEffect(() => {
if (count === 2) {
throw new Error('I crashed!');
}
});
return (
<button
onClick={onClick}
>
Click Me
</button>
);
}
export default Button;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)