使用钩子在反应功能组件中多次渲染 [英] Multiple times render in react functional component with hooks
问题描述
实际上我没有理解这个问题的正确点.所以寻求帮助.我有这个状态全功能组件.我在这里注意到的一点是,当我使用 useEffect 钩子获取数据时,我会正确地得到响应.
Actually I am not getting the right point of this problem. So seeking help. I have this state full functional component. The thing I have noticed here is that when I fetch data using useEffect hook then I get the response properly.
问题是,当我在 return 语句中执行 console.log("ok") 时,它会在控制台中多次提供输出.图片添加如下:
The problem is, when I execute console.log("ok") in the return statement it provides output multiple times in the console. The images are added bellow:
这是我的状态和 useEffect 钩子
Here is my state and useEffect hook
这是我的返回函数
这是我每次浏览页面时得到的控制台输出.
Here is the console output I get on each time I browse the page.
为什么 console.log("ok") 会执行多次?
Why the console.log("ok") is executing multiple times?
推荐答案
不是执行多次
,而是执行了5次:
It isn't executing multiple
times, it is executing 5 times:
useEffect
(第一次渲染)setMovies
setHeroImage
setCusrrentPage
setTotalPages
useEffect
(first render)setMovies
setHeroImage
setCusrrentPage
setTotalPages
useEffect
有 []
的 deps,所以这只发生在第一次渲染时.然后您要更改状态 4 次,因此会发生重新渲染.这并不意味着 DOM 更改了 5 次.
useEffect
has deps of []
so this only happens on the first render only. Then you are changing state 4 times, so a re-render happens. This does not mean that the DOM is changed 5 times.
这篇关于使用钩子在反应功能组件中多次渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!