在 React 應用程式中,Error Boundary 是一種用來捕捉錯誤的元件,今天我們來學習如何測試 Error Boundary。先看一下元件的程式碼:
error-boundary.js
import React from 'react'
import {reportError} from './api'
class ErrorBoundary extends React.Component {
state = {hasError: false}
componentDidCatch(error, info) {
this.setState({hasError: true})
reportError(error, info)
}
tryAgain = () => this.setState({hasError: false})
render() {
return this.state.hasError ? (
<div>
<div role="alert">There was a problem.</div>{' '}
<button onClick={this.tryAgain}>Try again?</button>
</div>
) : (
this.props.children
)
}
}
export {ErrorBoundary}
(未完...