为什么即使使用 ErrorBoundary 路由也会停止工作?

IT技术 reactjs error-handling routing react-router
2021-05-24 04:11:08

我们的应用程序使用ErrorBoundary来捕获错误。这工作正常,并且它应该在定义的位置显示错误消息。但是在错误表现出来之后,路由停止工作,基本上破坏了应用程序!

我觉得有点奇怪,考虑到该应用程序似乎可以正常工作:当我单击链接和/或使用后退按钮时,DevTools 显示routing/LOCATION_CHANGED正在调度的操作(我正在侦听history对象),并且 url 已更新,但没有正在渲染新的路线/屏幕。

由于 React 和 Redux 正在工作,所以我来指出 React Router,因为它是处理路由的主要组件。有谁知道我怎样才能阻止它破裂?

示例错误

此错误来自连接的组件,发生在 mapStateToProps

connectAdvanced.js?fe33:242 Uncaught TypeError: Cannot read property '3528' of undefined
    at getUserInRoleById (VM7787 users-reducer.js:108)
    at getUserByUserInRoleId (VM7787 users-reducer.js:110)
    at Function.mapStateToProps [as mapToProps] (VM8180 EncounterNotesHistoryItem.jsx:360)

其次是

The above error occurred in the <Connect(EncounterNotesHistoryItem)> component:
    in Connect(EncounterNotesHistoryItem)
    in div
    in Unknown (created by WithStyles(Component))
    in WithStyles(Component) (created by EncounterNotesHistory)
    in div (created by EncounterNotesHistory)

组件层次结构(选定的部分)

应用程序.jsx

<Provider store={store}>
  <ConnectedRouter history={customHistory} dispatch={dispatch}>
    <ErrorBoundary>
      <Route exact path="/appinfo" component={AppInfoScreen} />
      <Redirect exact from="/" to={`/encounter?attenderId=${userId}`} />
      <Route exact path="/search" component={SearchScreen} />
      <Route exact path="/search/:searchText" component={SearchScreen} />
      // and so on
    </ErrorBoundary>
  </ConnectedRouter>
</Provider>

依赖关系

"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-redux": "^5.0.7",
"react-router": "^5.0.1",
"react-router-dom": "^5.0.1",
"redux": "^3.6.0",
"reselect": "^3.0.1",
1个回答

背后的想法Error boundaries是提供一种优雅的方式来处理神秘的错误

错误边界的工作方式类似于 JavaScript catch {} 块,但适用于组件。

这意味着每次在组件树中抛出错误时Error boundary,整个树都将被fallback替换(例如自定义错误消息)。因此,每次您的Route组件之一抛出错误时,整个树都将被视为有错误,并且将不再呈现(卸载)。

您可以将个人包装Routes在错误边界中,以防止它们使应用程序的其余部分(包括其他Routes崩溃

此处查看有关理想粒度的更多信息Error boundaries