我已设置路由以使用错误边界包装所有组件
function renderComponentWithErrorBoundary(Component) {
return () => {
return (
<ErrorBoundary>
<Component />
</ErrorBoundary>
)
}
}
<Route path="/" exact render={renderComponentWithErrorBoundary(HomePage)} />
<Route path="/video/:programId/episode/:episodeId" render={renderComponentWithErrorBoundary(EpisodeVideoPage)} />
现在问题是一旦错误被捕获,边界似乎适用于所有路由,这意味着无论我导航到哪条路线,我仍然会看到错误边界错误状态。我认为在这个设置中它应该与特定组件隔离?
import React from 'react'
import PropTypes from 'prop-types'
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
this.state = {
hasError: false,
shouldFocus: false
}
}
componentDidUpdate() {
if (this.state.hasError && this.state.shouldFocus) {
focusElem(document.querySelector('#appNavLive'))
setTimeout(() => {
this.setState({
shouldFocus: false
})
})
}
}
componentDidCatch(error, info) {
this.setState({
hasError: true,
shouldFocus: true
})
console.log(`[ERROR] ${error.message}`)
console.log('[ERROR]', info)
}
render() {
if (this.state.hasError) {
return (
<div
id="app-error-boundary"
data-focusable
tabIndex="0"
ref={elem => { this.elem = elem }}
data-focus-left="appNavLive">
An Error Occurred
</div>
)
}
return this.props.children
}
}
答案 0 :(得分:0)
如果您有多个需要维护自己状态的相同类型的组件,则需要为它们提供唯一的键属性。因此,您应该为ErrorBoundary组件提供一个关键属性,该属性对于它所包含的特定组件是唯一的。