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 函数在组件挂载后和每次更新后都会调用,用于更新文档标题。

相关推荐
code2cat1 天前
React入门之任务列表:交换两行后,展开的详情跟着谁走
前端·javascript·react.js
niyongsheng2 天前
CopyCraft 字帖工坊:React + Electron 做一个全平台本地字帖生成器
react.js·electron·开源
用户298698530142 天前
在 React 中实现 Excel 文本与数字互转的完整实践
javascript·react.js·excel
少年的范儿2 天前
React Native + Expo 实战 04|让笔记界面响应操作:组件与状态
react native·react.js·typescript
陈如水2 天前
AI Agent 主流架构
前端·javascript·react.js
GuWenyue4 天前
setInterval 里的 state 永远是 0?我把 React 闭包陷阱的 5 个反例全写了一遍
前端·react.js
用户298698530145 天前
React 前端实现 Excel 与 OpenXML 双向转换:基于 WebAssembly 的浏览器端方案
javascript·react.js·excel
壹楽8 天前
用 React 19.2 的 <Activity> 做多页签保活,我踩了 6 个坑
react.js
spmcor8 天前
React useEffect 完全指南:从原理到实战的深度解析
react.js
用户2986985301410 天前
React 前端实现 Word 与 OpenXML 双向转换的完整实践
javascript·react.js