深入了解useEffect/useEffect的使用? [英] React useEffect in depth / use of useEffect?
本文介绍了深入了解useEffect/useEffect的使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图深入了解useEffect
挂钩.
我想知道什么时候使用哪种方法,为什么?
I would like to know when to use which method and why?
1.useEffect with no second paraments
useEffect(()=>{})
2.useEffect with second paraments as []
useEffect(()=>{},[])
3.useEffect with some arguments passed in the second parameter
useEffect(()=>{},[arg])
推荐答案
useEffect(callback)
- 在每个组件渲染器上运行.
- 通常用于调试,类似于在每个函数上执行函数的主体 渲染:
- Runs on every component render.
- Typically used for debugging, analogous to function's body execution on every render:
const Component = () => {
callback()
return <></>;
};
注意:执行时间仍然有所不同(请参阅下一个注意事项). 检查此沙箱日志.
Note: There is still a difference, in execution time (see the next note). Check this sandbox logs.
- 清理功能将在每个渲染器上运行.
- The cleanup function will run on every render.
useEffect(callback,[])
- 在组件安装上运行一次.
- 通常用于通过数据提取等初始化组件状态.
- 清理功能将在组件的卸载.
useEffect(callback,[arg])
- 对
arg
值进行更改. - Runs on change of
arg
value. - 清除功能在
arg
值更改时运行. - The cleanup function runs on
arg
value change. - 我的其他答案解释了
useEffect
回调的return
语句 - Dan Abramov编写的
useEffect
完整指南 -
useEffect
API - 使用效果钩子-React docs
- My additional answer explaining the
return
statement ofuseEffect
callback - A Complete Guide to
useEffect
by Dan Abramov useEffect
API- Using the effect hook - React docs
更改时" 是指 即将前一渲染的arg
值与当前渲染的prevArg === arg ? ~Do nothing~ : callback()
进行比较.
I.e compares the value of arg
from the previous render and the current one, prevArg === arg ? ~Do nothing~ : callback()
.
通常用于在道具/状态更改时运行事件.
Usually used to run events on props/state change.
注意:可以提供多种依存关系:
[arg1,arg2,arg3...]
Note: Multiple dependecies can be provided:
[arg1,arg2,arg3...]
这篇关于深入了解useEffect/useEffect的使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文