可能你已经知道, 在
React 16
中, 将会引进一个全新的架构 -React Fiber
, 它完全重写了 React 的协调算法
, 并引入了一些新的特性
. 这篇文章就是跟你们分享 React 16 中新的生命周期方法 -componentDidCatch
, 它能捕获在子组件树中任何地方的 JavaScript 异常,并打印这些错误和展现备用UI
, 就像将children
包裹在一个大的try/catch
语句块中. 你能够阅读 Dan Abramov 的 Error Handling in React 16 获取更多关于componentDidCatch
的内容.html
绝大多数的开发人员使用 React 16 都应该是由 15 升级上来的, 然而, 为了使用错误处理
而去重写整个组件确定是不明智的, 那么, 该怎么办呢, 固然有更好的处理方式, 那就是想办法封装组件
, 像修改组件定义
那是逼上梁上的行为.react
那么, 错误处理
究竟能够干些什么git
当有错误发生时, 咱们能够友好地展现 fallback
组件github
避免 normal
和 fallback
组件耦合
算法
咱们能够清楚地发现某些服务
的一些报错
架构
咱们能够复用报错
和 fallback
app
接下来, 咱们看一个最森破
的的实例优化
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> )
其实, 咱们还能够将其优化
一下, 好比将 ErrorHandler 参数化
, 将 reportErrorToService
做为 props
传递, 用 component
替代 上面返回的几行视图代码
. 因此, 咱们仍是要更新咱们的组件定义
, 以便将 UI
的一部分添加 ErrorHandler
中. 但正如咱们以前所讨论的, 咱们并不想修改组件的定义, 咱们只 decorate
它们this
对此, 咱们可使用高阶组件
spa
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> )
咱们可使用 withErrorHandler HOC
来封装组件, 使组件得到错误处理, 即当错误发生时, 调用 reportErrorToService
并展现 fallback
组件, 从而, 咱们帅气地避免了大量组件的定义修改
然而, 咱们还能够更帅气. 当服务报错跟 fallback
组件的视图都基本相同时, 咱们能够像下样同样 export withErrorHandler HOC
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> )
这样, 咱们就能够轻松地给组价添加
错误处理, 一样, 咱们也能够轻松地移除
那么, withErrorHandler
到底是如何工做
的呢, 其实, 实现它仍是挺简单的
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 }
这个高阶组件
能够用来封装任何组件, 捕获全部异常, 你能够用其封装整个 page
, 也能够用其封装个别组件
.
点击该 repository 能够查看更多源码
原文连接
: Catching exceptions using Higher Order Components in React 16 (Giorgi Bagdavadze)