我是 React 的新手。我想捕获所有反应未捕获和意外的错误/警告,我想将错误记录到外部 api。我知道它可以通过 Try Catch 方法实现,但我计划在全局范围内使用它,这样其他开发人员就不必每次都编写代码。
我尝试了 window.onerror/addEventListener('error', function(e){}
,它只捕获 Javascript 错误但不响应错误。
这类似于以下帖子 How do I handle exceptions? .但是给出的解决方案并不能满足我的需求。
有人可以帮我解决这个问题吗?
最佳答案
文档引用:https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html
实战案例:
// app.js
const MOUNT_NODE = document.getElementById('app');
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<ConnectedRouter history={history}>
<ErrorBoundary>
<App />
</ErrorBoundary>
</ConnectedRouter>
</LanguageProvider>
</Provider>,
MOUNT_NODE
);
};
// ErrorBoundary component
export default class ErrorBoundary {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return (
<div>
// error message
</div>
);
}
return this.props.children;
}
}
关于javascript - 全局捕获 React 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234855/