React的生命周期

162 阅读2分钟

React的生命周期是一个描述组件从创建到销毁的整个过程的概念,这个过程被分为几个关键阶段,每个阶段都有其特定的生命周期方法(也称为“钩子”或“回调函数”)。

生命周期总体概览

react的生命周期分为三个阶段:挂载、更新、销毁

image.png

挂载阶段(Mounting)

  • constructor(props) : 组件被实例化后立即调用,用于初始化state或绑定事件处理函数。在constructor中,应该总是首先调用super(props)
  • static getDerivedStateFromProps(props, state) : React 16.3引入的静态方法,用于根据props的变化来更新state,它会在挂载和更新过程中被调用。由于它是静态的,因此不能访问组件实例。
  • render() : 组件的核心方法,用于输出组件的UI结构。React会根据这个方法返回的JSX或null来更新DOM。
  • componentDidMount() : 组件挂载到DOM上后立即调用,是执行副作用操作(如数据获取、订阅或设置定时器)的好地方。
import React, { Component } from 'react'

export default class App extends Component {
  constructor(){
    super()
    console.log('constructor')
  }

  componentDidMount(){
    console.log('componentDidMount')
  }
  
  render() {
    console.log('render')
    return (
      <div>App</div>
    )
  }
}

结果:

image.png

更新阶段(Updating)

  • static getDerivedStateFromProps(props, state) (与挂载阶段相同): 在组件更新过程中,也会根据新的props来更新state。
  • shouldComponentUpdate(nextProps, nextState) : 返回一个布尔值,用于判断组件是否需要根据新的props或state重新渲染。默认值为true,但你可以通过比较props和state来优化性能,避免不必要的渲染。
  • render() (与挂载阶段相同): 组件更新时,会根据新的props和state重新渲染UI。
  • getSnapshotBeforeUpdate(prevProps, prevState) : React 16.3引入的方法,在最新的渲染输出提交给DOM之前调用,它使你的组件能在更新之前捕获一些信息(如滚动位置)。这个方法返回的任何值都将作为第三个参数传递给componentDidUpdate()。
  • componentDidUpdate(prevProps, prevState, snapshot) : 组件更新完成后调用,你可以在这里执行依赖于DOM的操作或基于props和state的变化来执行一些逻辑。
import React, { Component } from 'react'

export default class App extends Component {
  constructor(props){
    super(props)
    console.log('constructor')
    this.state = {
      count: 1
    }
  }

  componentDidMount(){
    console.log('componentDidMount')
  }

  shouldComponentUpdate(nextProps, nextState){
    console.log('shouldComponentUpdate')
    return nextState.count !== this.state.count
  }

  componentDidUpdate(){
    console.log('componentDidUpdate')
  }

  incrementCount = () => {
    this.setState({
      count: this.state.count + 1
    });
  };

  render() {
    console.log('render')
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    )
  }
}

结果:

image.png

卸载阶段(Unmounting)

  • componentWillUnmount() : 组件即将被卸载和销毁之前调用。这是执行清理工作的好地方,如取消网络请求、清除定时器或移除事件监听器等。
import React, { Component } from 'react';

class TimerComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
    this.timerId = null;
  }

  componentDidMount() {
    this.timerId = setInterval(() => {
      this.setState(prevState => ({ seconds: prevState.seconds + 1 }));
    }, 1000);
  }

  componentWillUnmount() {
    // 在组件卸载前清除定时器,防止内存泄漏
    clearInterval(this.timerId);
    console.log('Timer component unmounted.');
  }

  render() {
    return <div>Seconds passed: {this.state.seconds}</div>;
  }
}

export default TimerComponent;

结果: 一刷新页面,组件就被卸载了,触发了componentWillUnmount方法 image.png