React-Hooks----useEffect()

文章目录

前言

useEffect() 是 React 中最常用的 Hook 之一,它可以让函数组件拥有类似于类组件中 componentDidMountcomponentDidUpdatecomponentWillUnmount 生命周期函数的功能。

用法

useEffect() 接受两个参数
第一个参数是一个函数,称为 Effect 函数,该函数定义了在组件渲染完成后需要执行的操作。
第二个参数是一个数组,包含了该 Effect 函数所依赖的数据,当这些数据发生变化时,Effect 函数将重新执行,如果指定的是[], 回调函数只会在第一次render()后执行,相当于componentDidMount

Effect 函数可以返回一个清除函数,用于在组件卸载时清除 Effect 函数产生的一些副作用,相当于componentWillUnmount

以下是一个使用 useEffect() 的示例代码:

import {
    
     useEffect, useState } from 'react';

function MyComponent() {
    
    
  const [count, setCount] = useState(0);

  useEffect(() => {
    
    
    console.log(`You clicked ${
      
      count} times.`);
    return () => {
    
    
      console.log('Component unmounted.');
    }
  }, [count]);

  return (
    <div>
      <p>You clicked {
    
    count} times.</p>
      <button onClick={
    
    () => setCount(count + 1)}>Click me</button>
    </div>
  );
}

在上面的示例代码中,当组件初次渲染完成或 count 发生变化时,useEffect() 函数将被调用,并且输出当前的点击次数。在组件卸载时,清除函数将被调用,并且输出组件已经卸载。

猜你喜欢

转载自blog.csdn.net/weixin_46369590/article/details/129987133