React Router 的错误边界 [英] Error Boundary with React Router
问题描述
我已经设置了我的路由来用错误边界包装所有组件
function renderComponentWithErrorBoundary(Component) {返回 () =>{返回 (<错误边界><组件/></ErrorBoundary>)}}<Route path="/" 精确渲染={renderComponentWithErrorBoundary(HomePage)}/><Route path="/video/:programId/episode/:episodeId" render={renderComponentWithErrorBoundary(EpisodeVideoPage)}/>
现在的问题是一旦发现错误,边界似乎适用于所有路由,这意味着无论我导航到哪条路由,我仍然会看到错误边界错误状态.我认为在这个设置中它应该与特定组件隔离?
从 'react' 导入 React从 'prop-types' 导入 PropTypes导出默认类 ErrorBoundary 扩展 React.Component {构造函数(道具){超级(道具)this.state = {有错误:假,shouldFocus: 假}}componentDidUpdate() {如果(this.state.hasError && this.state.shouldFocus){focusElem(document.querySelector('#appNavLive'))setTimeout(() => {this.setState({shouldFocus: 假})})}}componentDidCatch(错误,信息){this.setState({有错误:真,shouldFocus: 真})console.log(`[错误] ${error.message}`)console.log('[错误]', 信息)}使成为() {如果(this.state.hasError){返回 ({ this.elem = elem }}data-focus-left="appNavLive">发生错误
)}返回 this.props.children}}
当你有几个相同类型的组件需要维护自己的状态时,你需要给它们一个唯一的键属性.因此,您应该为 ErrorBoundary 组件提供一个关键属性,该属性对于它封装的特定组件是唯一的.
I have setup my routes to wrap all components with an Error Boundary
function renderComponentWithErrorBoundary(Component) {
return () => {
return (
<ErrorBoundary>
<Component />
</ErrorBoundary>
)
}
}
<Route path="/" exact render={renderComponentWithErrorBoundary(HomePage)} />
<Route path="/video/:programId/episode/:episodeId" render={renderComponentWithErrorBoundary(EpisodeVideoPage)} />
Problem now is once an error is caught the boundary seem to apply to all routes, meaning no matter which route I navigate to, I still see the error boundary error state. I thought in this setup it should be isolated to the particular component?
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
}
}
In react when you have several components of the same type that needs to maintain their own state, you need to give them a unique key property. So you should give your ErrorBoundary components a key property that is unique for the specific component it incapsulates.
这篇关于React Router 的错误边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!