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

};
相关推荐
计算机魔术师39 分钟前
AMD砸82亿买下李飞飞,这次不卖芯片卖什么?
前端
hzxpaipai1 小时前
杭州企业官网怎么建设?从策划到上线的5步建站方法
运维·服务器·前端·网络
怕浪猫1 小时前
2026年金九银十,我面了22个前端
前端·javascript·面试
IT_陈寒2 小时前
Vue 这个响应式陷阱,我的头发都掉没了
前端·人工智能·后端
前端的日常2 小时前
一个人+AI做情侣食谱小程序,30天纯赚
前端·javascript·后端
qq_316837752 小时前
阿里云百炼 fun-asr-realtime uniapp vue3 调用
javascript·vue.js·uni-app
庄园特聘拆椅狂魔2 小时前
Java 后端转全栈的第一课:从前端项目搭建到技术选
java·开发语言·前端
triumph_passion2 小时前
前端路由策略:Memory、Hash 与 History
前端
李剑一3 小时前
AntDesign老版本没有月份和年份区间选择组件?我封装了一个完美版,附源码!
前端·vue.js
牧艺3 小时前
浏览器端 3D 看车重磅升级:从三款展车到可试驾的八车展厅
前端·three.js·交互设计