[英]ComponentDidCatch not working inside react component
I have this component.我有这个组件。 Inside componentDidMount
I created an object and try to throw the error.在componentDidMount
中,我创建了一个 object 并尝试抛出错误。 But the my componentDidCatch
has not been called instead breaks my page!但是我的componentDidCatch
没有被调用反而破坏了我的页面!
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
errorInfo: null
};
}
componentDidCatch(error, errorInfo) {
// Catch errors in any child components and re-renders with an error message
this.setState({
error,
errorInfo
});
console.log({ error, errorInfo });
}
componentDidMount() {
const d = {}
console.log(d.d.d)
}
render() {
console.log("458454545454")
if (this.state.error) {
console.log("Error occurred")
}
return(<div>dffdfdfdfdfd</div>)
}
}
You should add static getDerivedStateFromError
if you want to render some UI after catching an error.如果您想在捕获错误后呈现某些 UI,则应添加static getDerivedStateFromError
。
Also, Error Boundaries not catch an errors thrown in the error boundary itself (that's why I add FaultyComponent
throwing an actual error).此外,错误边界不会捕获错误边界本身抛出的错误(这就是我添加FaultyComponent
抛出实际错误的原因)。
function FaultyComponent() { throw new Error("Test error"); return <span>Faulty</span>; } class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.log('componentDidCatch', { error, errorInfo }); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } function App() { return ( <ErrorBoundary> <FaultyComponent /> </ErrorBoundary> ); } ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
componentDidCatch componentDidCatch
This lifecycle is invoked after an error has been thrown by a descendant component.在后代组件抛出错误后调用此生命周期。
componentDidCatch
doesn't catch errors thrown by the same component. componentDidCatch
不会捕获同一组件抛出的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.