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>;

};
相关推荐
饼饼饼33 分钟前
React19 新手指南:JSX 没那么难,用好这几条规则就够了
前端·javascript·react.js
想吃火锅100533 分钟前
【前端手撕】new
前端
小小小小宇40 分钟前
AI大背景下端到端界面测试
前端
丷丩1 小时前
MapLibre GL JS第50课:用表达式创建虚线渐变线
javascript·gis·mapbox·maplibre gl js
小小小小宇1 小时前
前端端到端界面测试全解析与应用
前端
去伪存真1 小时前
如何将没有字幕的英文视频转换成中文视频?
前端·pytorch·llm
Coisinier1 小时前
RHCE中shell脚本基础(磁盘剩余空间监控,Web 服务状态检查,curl 访问 Web 服务并返回状态)
linux·运维·服务器·前端·nginx·操作系统
ywl4708120871 小时前
springSecurity+jwt,简单版demo
java·前端·servlet
想吃火锅10051 小时前
【前端手撕】promise.all
前端
lichenyang4531 小时前
动态加载 vs 延迟加载:为什么 demo 里「延迟」看起来没效果?
前端