【发布时间】:2017-10-19 17:12:51
【问题描述】:
我使用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 记录的这个:“我应该看到这个记录吗??”。但我没有看到记录,它破坏了应用程序:
我是不是误会了什么?
【问题讨论】:
-
嘿,你做的对我来说看起来不错,我刚刚测试过,但它失败了。所以我也对答案感兴趣:)
-
我正在使用这个库js.jsnlog.com 来捕获所有错误(即使在错误处理程序中)。这就是我的错误边界组件的样子pastebin.com/aBFtD7DB
标签: javascript reactjs create-react-app