MST

星途 面试题库

面试题:React组件生命周期之挂载阶段

请详细阐述React组件在挂载阶段(mounting)会依次调用哪些生命周期方法,并说明每个方法的作用以及使用场景。
11.3万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

constructor

  • 作用:在React组件实例化时最先调用,用于初始化state以及为事件处理函数绑定this。
  • 使用场景:当需要在组件创建时初始化一些内部状态,或者绑定事件处理函数到实例时使用。例如:
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({ count: this.state.count + 1 });
  }
  render() {
    return (
      <button onClick={this.handleClick}>
        Click me {this.state.count} times
      </button>
    );
  }
}

getDerivedStateFromProps

  • 作用:在调用render方法之前调用,并且在初始挂载及后续更新时都会被调用。它接收props和state作为参数,返回一个对象来更新state,或者返回null表示不更新state。
  • 使用场景:当props的变化需要引起state的更新时使用。例如,根据props中的某个值来初始化或更新组件内部的state。
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: this.props.initialValue };
  }
  static getDerivedStateFromProps(props, state) {
    if (props.initialValue!== state.value) {
      return { value: props.initialValue };
    }
    return null;
  }
  render() {
    return <div>{this.state.value}</div>;
  }
}

render

  • 作用:是组件中唯一必须实现的方法。它会返回一个描述组件UI的React元素,可以是原生DOM元素、自定义React组件或者null、false等。此方法应该是纯函数,不应该改变组件的state,也不能执行副作用操作。
  • 使用场景:用于描述组件的UI结构。根据组件的props和state来决定返回什么样的UI。例如:
class MyComponent extends React.Component {
  render() {
    return <div>Hello, {this.props.name}</div>;
  }
}

componentDidMount

  • 作用:在组件被插入到DOM后立即调用。在此方法中可以执行副作用操作,例如发起网络请求、添加事件监听器等。
  • 使用场景:需要操作DOM元素、与外部库集成或者进行数据请求的场景。例如,在组件挂载后获取某个DOM元素的尺寸:
class MyComponent extends React.Component {
  componentDidMount() {
    const element = this.refs.myDiv;
    console.log('Element width:', element.offsetWidth);
  }
  render() {
    return <div ref="myDiv">This is a div</div>;
  }
}

注意:在React新的使用方式中,推荐使用React.createRef() 来创建ref,而不是使用字符串形式的ref。