React 16 中的异常处理
异常处理在 React 15.x 及之前的版本中,组件内的异常有可能会影响到 React 的内部状态,进而导致下一轮渲染时出现未知错误。这些组件内的异常往往也是由应用代码本身抛出,在之前版本的 React 更多的是交托给了开发者处理,而没有提供较好地组件内优雅处理这些异常的方式。在 React 16.x 版本中,引入了所谓 Error Boundary 的概念,从而保证了发生在 UI 层的错误不会连锁导致整个应用程序崩溃;未被任何异常边界捕获的异常可能会导致整个 React 组件树被卸载。所谓的异常边界即指某个能够捕获它的子元素(包括嵌套子元素等)抛出的异常,并且根据用户配置进行优雅降级地显示而不是导致整个组件树崩溃。异常边界能够捕获渲染函数、生命周期回调以及整个组件树的构造函数中抛出的异常。 class ErrorBoundary 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; } } 然后我们就可以如常使用该组件: <ErrorBoundary> <MyWidget /> </ErrorBoundary>
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { error: null,errorInfo: null }; } componentDidCatch(error,errorInfo) { // Catch errors in any components below and re-render with error message this.setState({ error: error,errorInfo: errorInfo }) // You can also log error messages to an error reporting service here } render() { if (this.state.errorInfo) { // Error path return ( <div> <h2>Something went wrong.</h2> <details style={{ whiteSpace: 'pre-wrap' }}> {this.state.error && this.state.error.toString()} <br /> {this.state.errorInfo.componentStack} </details> </div> ); } // Normally,just render children return this.props.children; } } class BuggyCounter extends React.Component { constructor(props) { super(props); this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(({counter}) => ({ counter: counter + 1 })); } render() { if (this.state.counter === 5) { // Simulate a JS error throw new Error('I crashed!'); } return <h1 onClick={this.handleClick}>{this.state.counter}</h1>; } } function App() { return ( <div> <p> <b> This is an example of error boundaries in React 16. <br /><br /> Click on the numbers to increase the counters. <br /> The counter is programmed to throw when it reaches 5. This simulates a JavaScript error in a component. </b> </p> <hr /> <ErrorBoundary> <p>These two counters are inside the same error boundary. If one crashes,the error boundary will replace both of them.</p> <BuggyCounter /> <BuggyCounter /> </ErrorBoundary> <hr /> <p>These two counters are each inside of their own error boundary. So if one crashes,the other is not affected.</p> <ErrorBoundary><BuggyCounter /></ErrorBoundary> <ErrorBoundary><BuggyCounter /></ErrorBoundary> </div> ); } ReactDOM.render( <App />,document.getElementById('root') ); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |