React16 componentDidCatch抓取错误示例

本文通过一个具体的React应用示例,展示了如何使用错误边界组件来捕获并展示子组件中的JavaScript错误,确保应用的稳定性和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #modal-root {
            position: relative;
            z-index: 999;
        }

        .app {
            height: 10em;
            width: 10em;
            background: lightblue;
            overflow: hidden;
        }

        .modal {
            background-color: rgba(0,0,0,0.5);
            position: fixed;
            height: 100%;
            width: 100%;
            top: 0;
            left: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }

    </style>
</head>
<body>
    <div id="app-root"></div>
    <div id="modal-root"></div>
    <div id="root"></div>
</body>
<!-- <script src="js/react.development.js"></script> -->
<script src="https://cdn.bootcss.com/react/16.2.0/umd/react.development.js"></script>
<!-- <script src="js/react-dom.development.js"></script> -->
<script src="https://cdn.bootcss.com/react-dom/16.2.0/umd/react-dom.development.js"></script>
<!-- <script src="js/babel.min.js"></script> -->
<script src="https://unpkg.com/@babel/standalone/babel.js"></script>
<script type="text/babel">
    
    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')
    );

</script>
</html>

点击5下可以在console中看到报错信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值