Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.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
Javascript 组件加载时检测react js中的错误_Javascript_Reactjs - Fatal编程技术网

Javascript 组件加载时检测react js中的错误

Javascript 组件加载时检测react js中的错误,javascript,reactjs,Javascript,Reactjs,我正在从事一个项目,我想知道的是如何检测组件中是否存在错误,并重定向到主页,或者在出现错误时在主页上显示要重定向的页面。通过编程您可以创建一个错误边界,并将组件包装在错误边界中。在ErrorBoundary组件的componentDidCatch中,您可以加载主页,也可以呈现相应的消息和链接以返回主页 您的ErrorBoundary应该如下所示 import React from "react"; import PropTypes from "prop-types"; class ErrorB

我正在从事一个项目,我想知道的是如何检测组件中是否存在错误,并重定向到主页,或者在出现错误时在主页上显示要重定向的页面。通过编程

您可以创建一个
错误边界
,并将组件包装在
错误边界
中。在
ErrorBoundary
组件的
componentDidCatch
中,您可以加载主页,也可以呈现相应的消息和链接以返回主页

您的
ErrorBoundary
应该如下所示

import React from "react";
import PropTypes from "prop-types";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
    console.log(error, info);
  }
  //Render the error condition component
  render() {
    if (this.state.hasError) {
      return <h1>Unable to load this section of the page!!</h1>;
    } else {
      return this.props.children;
    }
  }
}
ErrorBoundary.propTypes = {
  children: PropTypes.object
};
export default ErrorBoundary;
 <ErrorBoundary>
     <MyComponent={props} />
 </ErrorBoundary>
从“React”导入React;
从“道具类型”导入道具类型;
类ErrorBoundary扩展了React.Component{
建造师(道具){
超级(道具);
this.state={hasError:false};
}
componentDidCatch(错误,信息){
this.setState({hasError:true});
console.log(错误、信息);
}
//渲染错误条件组件
render(){
if(this.state.hasError){
return无法加载页面的此部分!!;
}否则{
返回此.props.children;
}
}
}
ErrorBoundary.propTypes={
子项:PropTypes.object
};
导出默认错误边界;
并将组件包装在错误边界内,如下所示

import React from "react";
import PropTypes from "prop-types";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
    console.log(error, info);
  }
  //Render the error condition component
  render() {
    if (this.state.hasError) {
      return <h1>Unable to load this section of the page!!</h1>;
    } else {
      return this.props.children;
    }
  }
}
ErrorBoundary.propTypes = {
  children: PropTypes.object
};
export default ErrorBoundary;
 <ErrorBoundary>
     <MyComponent={props} />
 </ErrorBoundary>


您可以阅读更多关于
ErrorBoundary

您需要在此处使用“componentdidcatch()”生命周期方法。

使用
ErrorBoundary
您可能需要阅读有关如何处理此问题的官方文档,谢谢您阅读文档并实施。。如果我遇到任何严重的减速,我会回来的