【发布时间】:2019-12-30 16:45:54
【问题描述】:
我们的应用使用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",
【问题讨论】:
-
错误是什么?
-
添加了一个非常典型的示例错误,因为它主要发生在数据加载部分。
-
你在哪里包装你的 ErrorBoundary 组件,在组件级别还是在根,如果是根,那么它不应该因为发生错误而工作,你基本上需要重新加载页面,如果在组件级别,那么该特定组件将不再工作
-
我认为您的 HOC 想法似乎是我要走的路线,因为我个人不希望个别路线处理自己的方式,除非他们需要定制的东西。但是,是的,ErrorBoundary 的心理模型就像组件级别的 try/catch 块,并且包含在其中的所有内容,如果失败,那么那些被包装的组件不应该工作,因为它已经被
componentDidCatch捕获了 -
这里是 HOC 的例子:github.com/bvaughn/react-error-boundary
标签: reactjs error-handling routing react-router