React基础与实践|青训营笔记

52 阅读3分钟

image.png

本篇文章中你可以学到,什么是web性能提升的关键,ErrorBoundary是什么?什么是类组件?以及用法。可以根据目录查看你需要的。


问题

影响 web 性能的两大主要原因是什么?

  • 等待资源加载实践大部分情况下浏览器单线程执行

ErrorBoundary

ract里面的ErrorBoundary是什么?

  • 在 React 中,ErrorBoundary 是一个组件
  • 用于处理渲染期间出现的 JavaScript 错误
  • 当在渲染组件期间抛出未捕获的错误时,React 会在组件树中向上寻找最近的 ErrorBoundary 组件,然后调用它的 componentDidCatch() 方法

componentDidCatch() 怎么用?

  • componentDidCatch() 接收两个参数:error(表示发生的错误)和 info(包含有关错误发生位置的组件树信息)

ErrorBoundary 还有哪些作用?

  • ErrorBoundary 组件可以将错误信息记录到日志中,或者渲染一些错误信息
  • ErrorBoundary 组件还可以帮助防止应用程序崩溃

作为抛出未捕获错误的ErrorBoundary和try-catch异常捕获之间什么关系?

  • React 的 ErrorBoundary 和 try-catch 的区别在于
  1. ErrorBoundary 可以捕获并处理子组件内部的错误,包括渲染错误和生命周期错误
  2. try-catch 只能捕获当前代码块内的同步错误
  3. ErrorBoundary 可以显示错误信息和 fallback UI,让用户知道发生了错误
  4. try-catch 只能通过 console.log 等方式输出错误信息
  5. ErrorBoundary 只能用于类组件,而 try-catch 可以用于函数和类组件

为什么ErrorBoundary 一定要写在类里面?

  • ErrorBoundary 是一个类组件,因此它必须被定义在类的范围内
  • 在 React 中,只有类组件才能成为高阶组件
  • ErrorBoundary 需要通过继承 React.Component 类来创建一个组件,因此必须使用类声明来定义

如果想在函数组件中使用 ErrorBoundary,可以考虑使用 React Hooks 中的 useErrorBoundary

下面是一个简单的ErrorBoundary的示例:

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

  static getDerivedStateFromError(error) {  
  // Update state so the next render will show the fallback UI.  
      return { hasError: true };  
  }
  componentDidCatch(error, errorInfo) {
      // You can also log the error to an error reporting service   
      logErrorToMyService(error, errorInfo); 
  }
  render() {
    if (this.state.hasError) {
    // You can render any custom fallback UI      return 
    <h1>Something went wrong.</h1>;   
    }
    return this.props.children; 
  }
}
  • 可以像常规组件一样访问这个组件

例如:

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

类组件

什么是类组件?

  • 在 React 中,有两种主要的组件类型:类组件函数组件
  • 类组件是以 ES6 类的形式定义的组件,它们是 React 最早支持的一种组件类型
  • 类组件通过继承 React.Component 类或 React.PureComponent 类创建
  • 在类组件中,可以使用生命周期方法、statepropsReact 功能
  • 它们通常被用于创建具有复杂交互逻辑和状态管理的组件
  • 与函数组件不同,类组件需要定义 render 方法来返回组件的内容

下面是一个简单的类组件的示例:

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  }
  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.handleClick}>Increase Count</button>
      </div>
    );
  }
}
export default MyComponent;
  1. MyComponent 是一个类组件
  2. 继承了 React 的 Component 类
  3. 定义了一个初始状态 count 为 0
  4. 在点击按钮时通过 handleClick 方法来更新该状态( setState )
  5. 在 render 方法中,它使用 this.state.count 和 this.handleClick 方法来渲染组件的内容

对应前文提到的:组件的返回内容必须定义在 render 中