我開始使用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
記錄:「我不應該看到這個記錄??」。但是,我沒有看到,記錄和它打破了應用:
我誤解的東西嗎?
嘿,你做了什麼看起來很對我,我只是測試,它失敗了。所以我也有興趣回答:) –