我从vite
创建了我的react应用程序,并从组件中 Package 了我的自定义React错误边界组件,问题是它无法捕获错误。我调试了我的错误组件,但它无法接收getDerivedStateFromError
中的任何值,而不是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;
有没有人知道问题是甚么?
1条答案
按热度按时间oxf4rvwz1#
错误边界不捕获以下对象的错误:
https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries
要模拟错误,您需要创建一个组件,使其成为ErrorBoundary类的子级,然后单击按钮2次