Multiple times render in react functional component with hooks [duplicate]

馋奶兔 提交于 2020-07-21 10:24:24

问题


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.

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:

Here is my state and useEffect hook

And here is my return function

Here is the console output I get on each time I browse the page.

Why the console.log("ok") is executing multiple times?


回答1:


It isn't executing multiple times, it is executing 5 times:

  1. useEffect (first render)
  2. setMovies
  3. setHeroImage
  4. setCusrrentPage
  5. setTotalPages

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.




回答2:


Because useState re-render the component, you should read the react doc to understand




回答3:


React is incredibly simplistic and basically re-renders everything all the time. Re-render is triggered if a component’s state has changed. You update state 4 times, thats why.



来源:https://stackoverflow.com/questions/58697073/multiple-times-render-in-react-functional-component-with-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!