react 组件生命周期

1. 挂载阶段(Mounting)

在函数式组件中,可以使用`useEffect`钩子函数来模拟`componentDidMount`的功能

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



const MyComponent = () => {

  const [data, setData] = useState(null);

  useEffect(() => {

    fetch("https://api.example.com/data")

      .then((response) => response.json())

      .then((data) => setData(data));

  }, []);

  return <div>{data && <p>{data.message}</p>}</div>;

};

2. 更新阶段(Updating)

在函数式组件中,可以在`useEffect`钩子函数中通过检查依赖项的变化来模拟`componentDidUpdate`的功能。

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

const MyComponent = () => {

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

  useEffect(() => {

    console.log("Component updated");

  }, [count]);

  return (

    <div>

      <p>Count: {count}</p>

      <button onClick={() => setCount(count + 1)}>Increment</button>

    </div>

  );

};

3. 卸载阶段(Unmounting)

在函数式组件中,如果使用`useEffect`钩子函数来设置定时器等副作用操作,可以通过返回一个清理函数来模拟`componentWillUnmount`的功能。

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

const MyComponent = () => {

  useEffect(() => {

    const timer = setInterval(() => {

      // 执行定时任务

    }, 1000);

    return () => clearInterval(timer);

  }, []);

  return <div>{/* 组件内容 */}</div>;

};
相关推荐
xurileidian4 小时前
第 24 篇 · 边玩边学Python · while 与死循环怎么退
服务器·前端·python
Highcharts.js6 小时前
Highcharts软件绘制图表:用数据构建可视化图形
前端·学习·信息可视化·数据分析·js·开发实战·highcharts
Hilaku7 小时前
2027 制药行业 ERP 系统架构选型笔记:从 GMP 合规追溯到动态 MCP 接入
前端·javascript·程序员
掘金安东尼9 小时前
人工智能AI
前端
kyriewen9 小时前
AI 面试官筛前端简历,先出局的不是写代码慢的
前端·面试·程序员
时间的情敌9 小时前
Three.js 后处理辉光 Bloom、告警发光效果、管线流光、着色器流动管线(ShaderMaterial)
开发语言·javascript·three.js·着色器
BigTopOne9 小时前
10 引用与借用:& 和 &mut
前端
粥里有勺糖9 小时前
视野修炼-技术周刊第139期 | AI 不会让时间变多
前端·github·ai编程
码哥字节10 小时前
Remotion Skills:用 React 代码做视频,简直太爽了
react.js
ZJPRENO11 小时前
WorkBuddy 从零到一|混元4 Flash 实战手记-提醒小工具开发
前端