我开始使用create-react-app一个应用程序,并且我有这个Error Boundary组分:阵营16错误边界部件(使用componentDidCatch)表示未被捕获的错误
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;
}
}
我用它在这个应用组件:
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
记录:“我不应该看到这个记录??”。但是,我没有看到,记录和它打破了应用:
我误解的东西吗?
嘿,你做了什么看起来很对我,我只是测试,它失败了。所以我也有兴趣回答:) –