Jie*_*eng 5 reactjs react-router
我已经设置了路线以用错误边界包装所有组件
function renderComponentWithErrorBoundary(Component) {
return () => {
return (
<ErrorBoundary>
<Component />
</ErrorBoundary>
)
}
}
<Route path="/" exact render={renderComponentWithErrorBoundary(HomePage)} />
<Route path="/video/:programId/episode/:episodeId" render={renderComponentWithErrorBoundary(EpisodeVideoPage)} />
Run Code Online (Sandbox Code Playgroud)
现在的问题是,一旦捕获错误,边界似乎适用于所有路线,这意味着无论我导航到哪条路线,我仍然会看到错误边界错误状态。我认为在这个设置中它应该与特定组件隔离?
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
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
在 React 中,当你有多个相同类型的组件需要维护自己的状态时,你需要给它们一个唯一的键属性。因此,您应该为 ErrorBoundary 组件提供一个对于它所封装的特定组件来说是唯一的关键属性。
| 归档时间: |
|
| 查看次数: |
2866 次 |
| 最近记录: |