我使用create-react-app启动了一个应用,我有这个Error Boundary组件:
import React from 'react'
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
console.log('shouldnt I see this logged??')
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
我在这个App组件中使用它:
import React from 'react'
import ErrorBoundary from './ErrorBoundary'
class App extends React.Component {
render() {
return (
<ErrorBoundary>
<div>
<button onClick={() => { throw new Error('lets throw an error') }}>
Click to throw error
</button>
</div>
</ErrorBoundary>
);
}
}
export default App;
我期待如果我单击App
中的按钮,应该捕获抛出的错误,我应该看到这是从ErrorBoundary
记录的:“我不应该看到这个记录吗?”。但我没有看到记录,它打破了应用程序:
我误解了什么吗?
答案 0 :(得分:3)
没有任何反应的原因是这是事件处理程序中的错误,并且它们不会被错误边界捕获。 error-handling blog post阐明了捕获的错误:
错误边界在渲染期间,生命周期方法以及它们下面的整个树的构造函数中捕获错误。
没有错误边界,捕获这些错误会非常棘手(在React 16中,即使生命周期方法错误也会使整个应用程序渲染消失。)
编辑:actual docs更清楚哪些错误被捕获。另请注意,server {
..other configs..
location /reactApp {
root /var/www;
index reactApp/index.html;
try_files $uri $uri/ /index.html;
}
..other configs..
}
使用create-react-app
包,在开发服务器版本之后,会在短暂的时间后用错误屏幕替换整个呈现。为了更好地发现您的错误被捕获,您可以运行生产构建。
答案 1 :(得分:0)
错误边界不能捕获以下错误: