返回

React 类组件中的生命周期函数:全面解读

前端

前言

在上一篇文章中,我们详细介绍了 React 组件的实例属性 state,相信大家对 state 有了更深入的了解。今天,我们将继续深入探讨 React 类组件,重点关注组件的生命周期函数。生命周期函数是 React 组件中非常重要的组成部分,它们允许我们对组件在不同阶段的行为进行控制和操作。

生命周期函数概述

React 类组件的生命周期函数一共有 9 个,分别对应组件的不同阶段。这 9 个生命周期函数可以分为三类:

  • 挂载阶段: componentDidMount、componentWillUnmount
  • 更新阶段: componentDidUpdate、shouldComponentUpdate、getDerivedStateFromProps
  • 卸载阶段: componentWillUnmount

其中,挂载阶段的生命周期函数会在组件首次挂载到 DOM 时被调用;更新阶段的生命周期函数会在组件更新时被调用;卸载阶段的生命周期函数会在组件从 DOM 中卸载时被调用。

挂载阶段的生命周期函数

componentDidMount

componentDidMount 是挂载阶段的生命周期函数,会在组件首次挂载到 DOM 时被调用。它通常用于执行一些初始化操作,例如:

  • 获取数据
  • 设置事件监听器
  • 启动定时器
componentDidMount() {
  // 获取数据
  this.getData();

  // 设置事件监听器
  this.addEventListener('click', this.handleClick);

  // 启动定时器
  this.timer = setInterval(this.tick, 1000);
}

componentWillUnmount

componentWillUnmount 是挂载阶段的生命周期函数,会在组件从 DOM 中卸载时被调用。它通常用于执行一些清理操作,例如:

  • 移除事件监听器
  • 清除定时器
  • 取消网络请求
componentWillUnmount() {
  // 移除事件监听器
  this.removeEventListener('click', this.handleClick);

  // 清除定时器
  clearInterval(this.timer);

  // 取消网络请求
  this.cancelNetworkRequest();
}

更新阶段的生命周期函数

componentDidUpdate

componentDidUpdate 是更新阶段的生命周期函数,会在组件更新时被调用。它通常用于执行一些更新操作,例如:

  • 更新组件的状态
  • 更新组件的视图
componentDidUpdate(prevProps, prevState) {
  // 更新组件的状态
  this.setState({ count: this.state.count + 1 });

  // 更新组件的视图
  this.render();
}

shouldComponentUpdate

shouldComponentUpdate 是更新阶段的生命周期函数,会在组件收到新的 props 或 state 时被调用。它返回一个布尔值,决定组件是否需要更新。如果 shouldComponentUpdate 返回 false,则组件不会更新,否则组件将更新。

shouldComponentUpdate(nextProps, nextState) {
  // 比较新的 props 和 state 与旧的 props 和 state,如果不同则返回 true,否则返回 false
  return !shallowEqual(nextProps, this.props) || !shallowEqual(nextState, this.state);
}

getDerivedStateFromProps

getDerivedStateFromProps 是更新阶段的生命周期函数,会在组件接收到新的 props 时被调用。它返回一个对象,用于更新组件的状态。

static getDerivedStateFromProps(nextProps, prevState) {
  // 根据新的 props 计算新的 state
  return { count: nextProps.count + 1 };
}

卸载阶段的生命周期函数

componentWillUnmount

componentWillUnmount 是卸载阶段的生命周期函数,会在组件从 DOM 中卸载时被调用。它通常用于执行一些清理操作,例如:

  • 移除事件监听器
  • 清除定时器
  • 取消网络请求
componentWillUnmount() {
  // 移除事件监听器
  this.removeEventListener('click', this.handleClick);

  // 清除定时器
  clearInterval(this.timer);

  // 取消网络请求
  this.cancelNetworkRequest();
}

结语

生命周期函数是 React 类组件中非常重要的组成部分,它们允许我们对组件在不同阶段的行为进行控制和操作。掌握生命周期函数,助你构建高性能、可维护的 React 应用。