【问题标题】:How to work with Error boundaries in react?如何在反应中使用错误边界?
【发布时间】:2020-11-09 20:39:49
【问题描述】:

我正在尝试为一个简单的应用程序添加错误边界。当我单击一个按钮时,屏幕上应该会显示“出了点问题”。但在我的情况下,它并没有那样显示。据我了解ErrorBoundary.js无法正常工作,因为我尝试控制台记录它。当我在屏幕上运行此应用程序时,它显示 错误:不是正确的点击

App.js


import './App.css';
import Button from './Components/Button';
import ErrorBoundary from './Components/ErrorBoundary';

function App() {
  return (
    <div className="App">
      
        <ErrorBoundary>
        <Button />
        </ErrorBoundary>
    </div>
  );
}

export default App;

Button.js

import React, { Component } from 'react';

class Button extends Component {

    constructor(props) {
        super(props);
        this.state = { error: null };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        console.log("Test Button")
        this.state = { error: true};
        throw new Error('Not a correct click');
    }


    render() {
        if (this.state.error) {
            return <h1>Caught an error!</h1>
        }
        return <button onClick={this.handleClick} style={{ color: 'white', background: 'blue', width: 200, height: 50 }}>Throw Error</button>
    }
}

export default Button;

ErrorBoundary.js

import React, { Component } from 'react'

class ErrorBoundary extends Component {

    constructor (props){
        super(props);

        this.state = {
            hasError: false,
            error: null,
            info: null
        }
    }

    static getDerivedStateFromError(error){
        this.state.hasError = true
    }

    componentDidCatch (error,info){
        console.log(error);
        console.log(info)
    }

    render() {
        if(this.state.hasError){
            return <h2>Something went wrong</h2>
        }
        return this.props.children;
    }
}

export default ErrorBoundary;

【问题讨论】:

    标签: javascript reactjs error-handling


    【解决方案1】:

    一切看起来都正确,但根据docs

    错误边界不会捕获以下错误:

    • 事件处理程序 (learn more)
    • 异步代码(例如 setTimeout 或 requestAnimationFrame 回调)
    • 服务器端渲染
    • 在错误边界本身(而不是其子项)中引发的错误

    根据我的经验,错误边界会在 render() 中捕获错误并阻止它传播到边界之外。

    错误边界背后的意图是避免 React 渲染状态半损坏。

    建议使用try/catch 来捕获事件处理程序中的错误。

    throw 移动到 Button.render 应该有助于 ErrorBoundary 捕获示例中的错误:

    handleClick() {
        console.log("Test Button")
        this.state = { error: true};
        // throw new Error('Not a correct click');
    }
    
    render() {
        if (this.state.error) {
            throw new Error('Not a correct click')
            return <h1>Caught an error!</h1>
        }
        return <button onClick={this.handleClick} style={{ color: 'white', background: 'blue', width: 200, height: 50 }}>Throw Error</button>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      相关资源
      最近更新 更多