八、错误处理

React16之前,组件在运行期间执行出错就会阻塞整个应用的渲染,只有刷新页面才能恢复应用。React16引入了新的错误机制

  • 默认情况下,当组件抛出错误,整个组件就会从组件树卸载,避免整个应用崩溃
  • 错误边界。能够捕获子组件的错误并对其做优雅处理的组件。可以是输出错误日志,显示出错提示等

定义了componentDidiCatch(error,info)这个方法的组件将成为一个错误边界

class ErrorBoundary extends React.Componnet {
    constructor(props){
      super(props);
      this.state = {hasError: false};
    }
    componentDidCatch(error,info){
      this.setState({hasError: true});
      console.log(error,info);
    }
    render(){
      if(this.state.hasError){
        return <h1>Oops,something went wrong.</h1>;
      }
      return this.props.children;
    }
}

在App中使用ErrorBoundary:

class App extends React.Componnet {
    constructor(props){
      super(props);
      this.state = {user: {name: 'react'}};
    }
    onClick = () => {
      this.setState({user: null});
    }
    render(){
      return {
        <div>
         <ErrorBoundary>
           <Profile user={this.state.user}/>
         </ErrorBoundary>
         <button onClick={this.onClick}>更新</button>
       </div>
      };
    }
}
const Profile = ((user) => <div>{user.name}</div>)

点击更新使user为null,抛出typeError,这个错误会被ErrorBoundary捕获,并在页面上显示出错误提示。(使用creat-react-app创建的项目,当程序发生错误是,会在页面上创建一个服从显示错误信息,要观察ErrorBoundary,需要先关闭错误浮层)

posted on 2022-10-22 16:23  Zoie_ting  阅读(87)  评论(0编辑  收藏  举报