Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在react中处理错误?_Reactjs - Fatal编程技术网

Reactjs 如何在react中处理错误?

Reactjs 如何在react中处理错误?,reactjs,Reactjs,我在react中搜索错误处理。 我找到了我想要的东西。 但componentDidCatch仅在渲染中捕获 我想抓住方法中的一个错误 我的消息来源 import React from 'react'; class Child extends React.Component{ handleError = () => { throw new Error('Error'); } render() { return (

我在react中搜索错误处理。 我找到了我想要的东西。 但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/>);
    }
}
从“React”导入React;
子类扩展了React.Component{
handleError=()=>{
抛出新错误(“错误”);
}
render(){
返回(
错误
);
}
}
导出默认的Main.Component{
componentDidCatch(错误,信息){
console.log(错误,信息);//不工作
}
render(){
返回();
}
}

您可以查看官方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扩展React.Component{
建造师(道具){
超级(道具);
this.state={hasError:false};
}
componentDidCatch(错误,信息){
//显示回退用户界面
this.setState({hasError:true});
//您还可以将错误记录到错误报告服务
logErrorToMyService(错误,信息);
}
render(){
if(this.state.hasError){
//您可以呈现任何自定义回退UI
返回出了问题的地方。;
}
返回此.props.children;
}
}

这个代码盒是丹·阿布拉莫夫(React的创建者)的官方代码盒:

我检查了代码。但不能捕捉到方法错误。componentDidCatch仅在呈现方法错误中起作用。