网络推广网站大全,有动效得网站,品牌营销策划方案模板,程建网文章目录前言用法前言
useEffect() 是 React 中最常用的 Hook 之一#xff0c;它可以让函数组件拥有类似于类组件中 componentDidMount、componentDidUpdate 和 componentWillUnmount 生命周期函数的功能。
用法
useEffect() 接受两个参数 第一个参数是一个函数#xff0c…
文章目录前言用法前言
useEffect() 是 React 中最常用的 Hook 之一它可以让函数组件拥有类似于类组件中 componentDidMount、componentDidUpdate 和 componentWillUnmount 生命周期函数的功能。
用法
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 (divpYou clicked {count} times./pbutton onClick{() setCount(count 1)}Click me/button/div);
}
在上面的示例代码中当组件初次渲染完成或 count 发生变化时useEffect() 函数将被调用并且输出当前的点击次数。在组件卸载时清除函数将被调用并且输出组件已经卸载。