在 React 16 中使用高阶组件来捕获异常

前端之家收集整理的这篇文章主要介绍了在 React 16 中使用高阶组件来捕获异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

可能你已经知道,在 React 16 中,将会引进一个全新的架构 - React Fiber,它彻底重写了 React 的协调算法,并引入了一些新的特性. 这篇文章就是跟大家分享 React 16 中新的生命周期方法 - componentDidCatch,它能捕获在子组件树中任何地方的 JavaScript 异常,并打印这些错误和展示备用UI,就像将 children 包裹在一个大的 try/catch 语句块中. 你可以阅读 Dan Abramov 的 Error Handling in React 16 获取更多关于 componentDidCatch内容.

绝大多数的开发人员使用 React 16 都应该是由 15 升级上来的,然而,为了使用错误处理而去重写整个组件肯定是不明智的,那么,该怎么办呢,当然有更好的处理方式,那就是想办法封装组件,像修改组件定义那是逼上梁上的行为.

那么,错误处理究竟可以干些什么

  • 当有错误发生时,我们可以友好地展示 fallback 组件
  • 避免 normalfallback 组件耦合
  • 我们可以清楚地发现某些服务的一些报错
  • 我们可以复用报错fallback

接下来,我们看一个最森破的的实例

  1. class ErrorHandler extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = { hasError: false };
  5. }
  6.  
  7. componentDidCatch(error,info) {
  8. // Display fallback UI
  9. this.setState({ hasError: true });
  10. // You can also log the error to an error reporting service
  11. logErrorToMyService(error,info);
  12. }
  13.  
  14. render() {
  15. if (this.state.hasError) {
  16. // You can render any custom fallback UI
  17. return <h1>Something went wrong.</h1>;
  18. }
  19. return this.props.children;
  20. }
  21. }
  22.  
  23. // Then you can use it as a regular component
  24. const MyPage = props => (
  25. <Container>
  26. <ErrorHandler>
  27. <MyComponent />
  28.  
  29. <MyOtherComponent />
  30. </ErrorHandler>
  31. </Container>
  32. )

其实,我们还可以将其优化一下,比如将 ErrorHandler 参数化,将 reportErrorToService 作为 props 传递,用 component 替代 上面返回的几行视图代码. 所以,我们还是要更新我们的组件定义,以便将 UI 的一部分添加 ErrorHandler 中. 但正如我们之前所讨论的,我们并不想修改组件的定义,我们只 decorate 它们

对此,我们可以使用高阶组件

  1. const MyFallbackComponent = props => (
  2. <h1>Something Went Wrong</h1>
  3. )
  4.  
  5. // we'll talk about `withErrorHandler` later
  6. const MyErrorHandler = withErrorHandler(
  7. reportErrorToService,MyFallbackComponent
  8. )
  9.  
  10. const MyComponent = MyErrorHandler(props => (
  11. /* ... */
  12. ))
  13.  
  14. const MyOthercomponent = MyErrorHandler(props => (
  15. /* ... */
  16. ))
  17.  
  18. const MyPage = props => (
  19. <Container>
  20. <MyComponent />
  21.  
  22. <MyOtherComponent />
  23. </Container>
  24. )

我们可以使用 withErrorHandler HOC 来封装组件,使组件获得错误处理,即当错误发生时,调用 reportErrorToService 并展示 fallback 组件,从而,我们帅气地避免了大量组件的定义修改

然而,我们还可以更帅气. 当服务报错跟 fallback 组件的视图都基本相同时,我们可以像下样一样 export withErrorHandler HOC

  1. import withErrorHandler from 'error-handler-hoc'
  2.  
  3. import reportErrorToService from '../services/errorReporter'
  4. import FallbackView from '../components/Fallback/'
  5.  
  6. export default withErrorHandler(
  7. reportErrorToService,FallbackView
  8. )

然后,我们 export 封装过后的组件就可以了

  1. // MyComponent.jsx
  2. import ErrorHandler from '../HOCs/ErrorHandler.js'
  3.  
  4. const MyComponent = props => (
  5. /* ... */
  6. )
  7.  
  8. export default ErrorHandler(MyComponent)
  9.  
  10. // ====================
  11. // MyOtherComponent.jsx
  12. import ErrorHandler from '../HOCs/ErrorHandler.js'
  13. import ...
  14.  
  15. const MyOtherComponent = props => (
  16. /* ... */
  17. )
  18.  
  19. // you might already be using HOCs
  20. export default compose(
  21. SomeOtherHOC,ErrorHandler
  22. )(MyOtherComponent)
  23.  
  24. // ====================
  25. // MyPage.jsx
  26. import { MyComponent,MyOtherComponent } from './components'
  27.  
  28. const MyPage = () => (
  29. <Container>
  30. <MyComponent />
  31. <MyOtherComponent />
  32. </Container>
  33. )

这样,我们就可以轻松地给组价添加错误处理,同样,我们也可以轻松地移除

那么,withErrorHandler 究竟是如何工作的呢,其实,实现它还是挺简单的

  1. function withErrorHandler (errorCallback,FallbackComponent,Component) {
  2. class WithErrorHandler extends React.Component {
  3. constructor () {
  4. super()
  5.  
  6. // Construct the initial state
  7. this.state = {
  8. hasError: false,error: null,errorInfo: null
  9. }
  10. }
  11.  
  12. componentDidCatch (error,info) {
  13. // Update state if error happens
  14. this.setState({ hasError: true,error,errorInfo: info })
  15.  
  16. // Report errors
  17. errorCallback(error,info,this.props)
  18. }
  19.  
  20. render () {
  21. // if state contains error we render fallback component
  22. if (this.state.hasError) {
  23. const { error,errorInfo } = this.state
  24. return (
  25. <FallbackComponent
  26. {...this.props}
  27. error={error}
  28. errorInfo={errorInfo}
  29. />
  30. )
  31. }
  32.  
  33. return <Component {...this.props} />
  34. }
  35. }
  36. WithErrorHandler.displayName = `withErrorHandler(${Component.displayName})`
  37. return WithErrorHandler
  38. }

总结

这个高阶组件可以用来封装任何组件,捕获所有异常,你可以用其封装整个 page,也可以用其封装个别组件.

点击该 repository 可以查看更多源码

原文链接: Catching exceptions using Higher Order Components in React 16

猜你在找的React相关文章