我该如何处理错误?

时间:2018-08-29 06:50:33

标签: reactjs

我在react中搜索错误处理。 我发现componentDidCatch。 但是componentDidCatch仅捕获渲染。

我想捕获方法错误。

我的来源

import React from 'react';
class Child extends React.Component{
    handleError = () => {
        throw new Error('Error');
    }
    render() {
        return (
            <button onClick={this.handleError}>Error</button>
        );
    }
}
export default Main extends React.Component {
    componentDidCatch(error,info) {
        console.log(error, info); // NOT WORK
    }
    render() {
        return (<Child/>);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在他们使用此代码的地方查看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;
  }
}

此代码框是Dan Abramov的官方代码(React的创建者):https://codepen.io/gaearon/pen/wqvxGa?editors=0010