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

};
相关推荐
S***t7141 小时前
Vue面试经验
javascript·vue.js·面试
粉末的沉淀1 小时前
css:制作带边框的气泡框
前端·javascript·css
p***h6433 小时前
JavaScript在Node.js中的异步编程
开发语言·javascript·node.js
N***73853 小时前
Vue网络编程详解
前端·javascript·vue.js
e***71673 小时前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
程序猿小蒜3 小时前
基于springboot的的学生干部管理系统开发与设计
java·前端·spring boot·后端·spring
银空飞羽3 小时前
让Trae CN SOLO自主发挥,看看能做出一个什么样的项目
前端·人工智能·trae
Eshine、4 小时前
解决前端项目中,浏览器无法正常加载带.gz名称的文件
前端·vue3·.gz·.gz名称的js文件无法被加载
用户47949283569154 小时前
React Grab 原理篇:它是怎么"偷窥" React 的?
人工智能·react.js·ai编程
q***38514 小时前
TypeScript 与后端开发Node.js
javascript·typescript·node.js