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

时间:2019-08-26 13:24:21

标签: reactjs error-handling routing react-router

我们的应用使用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)

组件层次结构(选定的片段)

App.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 个答案:

答案 0 :(得分:2)

Error boundaries背后的想法是提供一种优雅的方式来处理cryptic errors

  

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

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

您可以将单个Routes包装在错误边界中,以防止它们崩溃,从而导致应用程序的其余部分(包括其他Routes)崩溃。

详细了解Error boundaries here

的理想粒度
相关问题