React 组件生命周期函数的用法和示例代码

React 中的生命周期函数可以分为三个阶段:Mounting(挂载),Updating(更新)和 Unmounting(卸载)。每个阶段都有不同的函数,用于执行不同的操作。

  1. Mounting(挂载)

Mounting 阶段是组件实例化并插入到 DOM 中的阶段。在这个阶段中,有以下几个函数:

  • constructor():构造函数,用于初始化组件的 state 和绑定事件处理函数。
javascript 复制代码
constructor(props) {
  super(props);
  this.state = { count: 0 };
  this.handleClick = this.handleClick.bind(this);
}
  • static getDerivedStateFromProps():当组件接收到新的 props 时,会调用此函数,返回一个对象来更新 state,或者返回 null 表示不更新 state。
javascript 复制代码
static getDerivedStateFromProps(nextProps, prevState) {
  if (nextProps.value !== prevState.value) {
    return { value: nextProps.value };
  }
  return null;
}
  • render():渲染组件到 DOM 中。
javascript 复制代码
render() {
  return (
    <div>
      <p>Count: {this.state.count}</p>
      <button onClick={this.handleClick}>Click me</button>
    </div>
  );
}
  • componentDidMount():组件挂载到 DOM 后调用,通常用于发送网络请求、设置定时器等操作。
javascript 复制代码
componentDidMount() {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => this.setState({ data }));
}
  1. Updating(更新)

Updating 阶段是组件状态或属性更新时的阶段。在这个阶段中,有以下几个函数:

  • shouldComponentUpdate():当组件接收到新的 props 或 state 时,会调用此函数,返回 true 表示需要更新组件,返回 false 表示不需要更新组件。
javascript 复制代码
shouldComponentUpdate(nextProps, nextState) {
  if (nextProps.value !== this.props.value || nextState.count !== this.state.count) {
    return true;
  }
  return false;
}
  • static getDerivedStateFromProps():同 Mounting 阶段的 getDerivedStateFromProps() 函数。
  • render():同 Mounting 阶段的 render() 函数。
  • componentDidUpdate():组件更新后调用,通常用于操作 DOM 或发送网络请求。
javascript 复制代码
componentDidUpdate(prevProps, prevState) {
  if (prevProps.value !== this.props.value) {
    fetch(`https://api.example.com/data?value=${this.props.value}`)
      .then(response => response.json())
      .then(data => this.setState({ data }));
  }
}
  1. Unmounting(卸载)

Unmounting 阶段是组件从 DOM 中移除的阶段。在这个阶段中,有以下几个函数:

  • componentWillUnmount():组件卸载前调用,通常用于清理定时器或取消网络请求等操作。
javascript 复制代码
componentWillUnmount() {
  clearTimeout(this.timer);
}

需要注意的是,在 React 16.8 之后,引入了 Hooks 的概念,可以使用 useEffect 等 Hook 来代替生命周期函数。例如:

javascript 复制代码
import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

在这个例子中,useEffect 函数在组件挂载后和每次更新后都会调用,用于更新文档标题。

相关推荐
小林ixn3 小时前
从零到一理解 React 父子组件通信:手写一个 Todo 应用带你彻底搞懂单向数据流
前端·javascript·react.js
qetfw6 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具
鱼毓屿御7 小时前
从「只会聊」到「边想边做」的跃迁
前端·学习·react.js
嘟嘟07178 小时前
搞懂 useState 从原生 DOM 到 React 惰性初始化的完整链路
前端·react.js·编程语言
先吃饱再说11 小时前
React 组件设计:从 Props 传递到组件封装
前端·react.js
小月土星14 小时前
React 状态管理核心原理:从批量 DOM 到派生状态
react.js
烬羽15 小时前
AI 写代码总翻车?试试"先画图再砌墙"的 Vibe Coding 三步法
react.js·ai编程·vibecoding
光影少年16 小时前
react navite 页面跳转、传参、路由监听、导航栏自定义
前端·react native·react.js
LaughingZhu17 小时前
Product Hunt 每日热榜 | 2026-07-23
前端·神经网络·react.js·搜索引擎·前端框架
不好听61317 小时前
Fragment:React 的 `<></>` 和原生的 DocumentFragment,同名不同命
前端·react.js·dom