在 React 16 中使用高阶组件来捕获异常
绝大多数的开发人员使用 React 16 都应该是由 15 升级上来的,然而,为了使用 那么,
接下来,我们看一个 class ErrorHandler extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error,info) { // Display fallback UI this.setState({ hasError: true }); // You can also log the error to an error reporting service logErrorToMyService(error,info); } render() { if (this.state.hasError) { // You can render any custom fallback UI return <h1>Something went wrong.</h1>; } return this.props.children; } } // Then you can use it as a regular component const MyPage = props => ( <Container> <ErrorHandler> <MyComponent /> <MyOtherComponent /> </ErrorHandler> </Container> ) 其实,我们还可以将其 对此,我们可以使用 const MyFallbackComponent = props => ( <h1>Something Went Wrong</h1> ) // we'll talk about `withErrorHandler` later const MyErrorHandler = withErrorHandler( reportErrorToService,MyFallbackComponent ) const MyComponent = MyErrorHandler(props => ( /* ... */ )) const MyOthercomponent = MyErrorHandler(props => ( /* ... */ )) const MyPage = props => ( <Container> <MyComponent /> <MyOtherComponent /> </Container> ) 我们可以使用 然而,我们还可以更帅气. 当服务报错跟 import withErrorHandler from 'error-handler-hoc' import reportErrorToService from '../services/errorReporter' import FallbackView from '../components/Fallback/' export default withErrorHandler( reportErrorToService,FallbackView ) 然后,我们 export // MyComponent.jsx import ErrorHandler from '../HOCs/ErrorHandler.js' const MyComponent = props => ( /* ... */ ) export default ErrorHandler(MyComponent) // ==================== // MyOtherComponent.jsx import ErrorHandler from '../HOCs/ErrorHandler.js' import ... const MyOtherComponent = props => ( /* ... */ ) // you might already be using HOCs export default compose( SomeOtherHOC,ErrorHandler )(MyOtherComponent) // ==================== // MyPage.jsx import { MyComponent,MyOtherComponent } from './components' const MyPage = () => ( <Container> <MyComponent /> <MyOtherComponent /> </Container> ) 这样,我们就可以轻松地给组价 那么, function withErrorHandler (errorCallback,FallbackComponent,Component) { class WithErrorHandler extends React.Component { constructor () { super() // Construct the initial state this.state = { hasError: false,error: null,errorInfo: null } } componentDidCatch (error,info) { // Update state if error happens this.setState({ hasError: true,error,errorInfo: info }) // Report errors errorCallback(error,info,this.props) } render () { // if state contains error we render fallback component if (this.state.hasError) { const { error,errorInfo } = this.state return ( <FallbackComponent {...this.props} error={error} errorInfo={errorInfo} /> ) } return <Component {...this.props} /> } } WithErrorHandler.displayName = `withErrorHandler(${Component.displayName})` return WithErrorHandler } 总结这个 点击该 repository 可以查看更多源码
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |