【前端】【面试】【复习详解】【react】react生命周期--函数式全解

在 React Hooks 引入之后,函数式组件可以使用 useEffect 等钩子来模拟类组件生命周期方法的功能。下面详细介绍如何用函数式组件实现类似类组件生命周期的效果。

挂载阶段

模拟 componentDidMount

componentDidMount 在类组件中是在组件挂载到 DOM 之后立即调用,通常用于执行副作用操作,如数据获取、订阅事件等。在函数式组件中,可以使用 useEffect 并传入一个空数组作为依赖项来模拟这个行为。

js 复制代码
import React, { useEffect } from 'react';

const MyFunctionalComponent = () => {
    useEffect(() => {
        // 这里的代码会在组件挂载后执行,类似于 componentDidMount
        console.log('Component is mounted');

        // 模拟数据获取
        fetch('https://api.example.com/data')
           .then(response => response.json())
           .then(data => console.log(data));

        // 返回一个清理函数(可选),用于在组件卸载时执行清理操作
        return () => {
            console.log('Component is unmounted');
        };
    }, []); // 空数组表示只在组件挂载和卸载时执行

    return <div>My Functional Component</div>;
};

export default MyFunctionalComponent;

更新阶段

模拟 componentDidUpdate

componentDidUpdate 在类组件中是在组件更新完成后调用。在函数式组件中,useEffect 没有依赖项数组时,每次组件渲染都会执行,传入依赖项数组后,只有当依赖项发生变化时才会执行,利用这个特性可以模拟 componentDidUpdate

js 复制代码
import React, { useState, useEffect } from 'react';

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

    useEffect(() => {
        // 这里的代码会在组件挂载和每次更新后执行
        console.log('Component is updated');

        // 可以根据依赖项进行条件判断
        if (count > 0) {
            console.log(`Count has been updated to ${count}`);
        }

        return () => {
            console.log('Cleanup before next update');
        };
    }, [count]); // 只有 count 发生变化时才会执行

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
};

export default MyFunctionalComponent;

卸载阶段

模拟 componentWillUnmount

componentWillUnmount 在类组件中是在组件即将从 DOM 中移除之前调用,用于清理资源,如取消订阅、清除定时器等。在函数式组件中,useEffect 的返回值是一个清理函数,这个清理函数会在组件卸载时执行,从而模拟 componentWillUnmount 的功能。

js 复制代码
import React, { useEffect, useState } from 'react';

const MyFunctionalComponent = () => {
    const [isMounted, setIsMounted] = useState(true);

    useEffect(() => {
        const timer = setInterval(() => {
            console.log('Timer is running');
        }, 1000);

        // 返回一个清理函数,在组件卸载时执行
        return () => {
            clearInterval(timer);
            console.log('Timer is cleared');
        };
    }, []);

    const handleUnmount = () => {
        setIsMounted(false);
    };

    return (
        <div>
            {isMounted && <p>Component is mounted</p>}
            <button onClick={handleUnmount}>Unmount Component</button>
        </div>
    );
};

export default MyFunctionalComponent;

其他情况

模拟 shouldComponentUpdate

在类组件中,shouldComponentUpdate 用于控制组件是否需要重新渲染。在函数式组件中,可以使用 React.memo 来实现类似的功能。React.memo 是一个高阶组件,它会对组件的 props 进行浅比较,如果 props 没有变化,就不会重新渲染组件。

js 复制代码
import React from 'react';

const MyMemoizedComponent = React.memo((props) => {
    return <div>{props.message}</div>;
});

export default MyMemoizedComponent;

综上所述,函数式组件通过 useEffectReact.memo 等 Hooks 可以很好地模拟类组件生命周期方法的功能,并且代码更加简洁和易于维护。

相关推荐
程序员黑豆5 小时前
Java类型推断完全指南:从var到菱形运算符,掌握使用限制与最佳实践
java·前端·ai编程
To_OC5 小时前
踩了个 TS 的坑之后,我终于把 type 和 interface 掰明白了
前端·react.js·typescript
GreenTea6 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
码匠许师傅6 小时前
【C++ 面试真题】聊聊 C++ 的移动语义与右值引用
java·c++·面试
浮生望6 小时前
前端API工程化:用 Mock 数据与 Axios 配置实现独立于后端的并行开发
前端
万少6 小时前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
波波0077 小时前
C# 15 重磅新特性: 带标签 break 与 continue:重新定义嵌套循环控制流
服务器·前端·c#
Brown.alexis7 小时前
es6知识点1-自备使用
前端·ecmascript·es6
小爬的老粉丝8 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
Thecozzy9 小时前
大厂 AI Coding 面试大招
人工智能·面试·职场和发展