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

标签 reactjs error-handling routes 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",

最佳答案

错误边界背后的想法是提供一种优雅的方式来处理 cryptic errors .

Error boundaries work like a JavaScript catch {} block, but for components.

这意味着每次在由错误边界包裹的组件树中抛出错误时,整个树都将被fallback值替换(自定义错误例如消息)。因此,每当您的 Route 组件之一抛出错误时,整个树都会被视为错误,并且将不再渲染(卸载)。

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

详细了解错误边界的理想粒度 here

关于reactjs - 为什么即使使用 ErrorBoundary 路由也会停止工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57658813/

相关文章:

javascript - 如何仅在收到 props 时渲染 React(使用 Redux)组件?

reactjs - 无法在 redux-form 字段中输入

c++ - 错误处理理论?

laravel - Laravel自定义错误

java - 在 Vert.x Web 路由器上的不存在路由上提供静态 webroot/index.html 数据

javascript - 使用静态 React 函数的返回值

javascript - React : You may need an appropriate loader to handle this file type, 当前没有配置加载程序来处理此文件(本地 Node 模块)

r - R-错误: “duplicate ' row.names' are not allowed”

android - 如何让路线绘制更高效?

ruby-on-rails - rails 上的 ruby 。 Unicode 路由