我有一个包裹在错误边界中的组件,当单击按钮时,会调用一个validate()
函数,如果没有提供任何信息,但是ErrorBoundary
却无法捕获此函数,则此函数会引发错误错误。
组件上的渲染功能
return (
<ErrorBoundary>
...
<Playlist
...
onClick={this.addPlaylistToSpotify} // this function can throw an error
...
/>
</ErrorBoundary>
);
功能出错
addPlaylistToSpotify = () => {
try {
addPlaylist(this.state.newPlaylist); // this function throws an error on validate()
} catch (error) {
throw new Error(error);
}
...
};
错误边界组件
import React, { Component } from "react";
import { ErrorOverlay } from "../../components/index";
import styles from "./ErrorBoundary.css";
export class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: ""
};
}
componentDidCatch(error, errorInfo) {
this.setState({
hasError: true,
error: error,
errorInfo: errorInfo
});
// TODO: log the error somewhere in the db
}
dismiss() {
this.setState({
hasError: false,
error: null,
errorInfo: ""
});
}
render() {
if (this.state.hasError) {
return (
<ErrorOverlay message={this.state.errorInfo} dismiss={this.dismiss} />
);
} else {
return this.props.children;
}
}
}
任何帮助将不胜感激,谢谢! 任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
来自React文档
https://reactjs.org/docs/error-boundaries.html#how-about-event-handlers
注意
错误边界不能捕获以下错误:
- 事件处理程序
- 异步代码(例如setTimeout或requestAnimationFrame回调)
- 服务器端渲染
- 错误边界本身(而不是其子级)引发的错误
在您的代码中,错误是从事件处理程序(addPlaylistToSpotify)引发的,因此componentDidCatch无法捕获错误。因此,您需要执行以下操作:
import React from 'react';
export class Playlist extends React.Component {
constructor (props) {
super(props);
this.state = {
error: false
// ...
}
}
addPlaylistToSpotify = () => {
try {
// Something throws an error here.
} catch (error) {
this.setState({ error: true });
}
}
render() {
if (this.state.error) {
throw new Error('I crashed!');
}
return (
<div>
...
<button onClick={this.addPlaylistToSpotify}>Add song</button>
...
</div>
)
}
}
我希望这会有所帮助。