欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > 【前端】【面试】【复习详解】【react】react生命周期--函数式全解

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

2025/5/7 3:03:19 来源:https://blog.csdn.net/qq_59344127/article/details/145482199  浏览:    关键词:【前端】【面试】【复习详解】【react】react生命周期--函数式全解

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

挂载阶段

模拟 componentDidMount

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

import React, { useEffect } from 'react';const MyFunctionalComponent = () => {useEffect(() => {// 这里的代码会在组件挂载后执行,类似于 componentDidMountconsole.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

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 的功能。

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 没有变化,就不会重新渲染组件。

import React from 'react';const MyMemoizedComponent = React.memo((props) => {return <div>{props.message}</div>;
});export default MyMemoizedComponent;

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词