React Router 的错误边界

IT技术 reactjs react-router
2021-05-17 20:26:22

我已经设置了我的路由来用错误边界包装所有组件

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
  }
}
1个回答

在 React 中,当您有多个相同类型的组件需要维护自己的状态时,您需要给它们一个唯一的键属性。因此,您应该为 ErrorBoundary 组件提供一个关键属性,该属性对于它封装的特定组件是唯一的。