即使使用,也不需要对功能组件进行不必要的重新渲染吗?

时间:2020-10-31 04:51:46

标签: reactjs rendering use-effect rerender

我正在努力创建高效的代码。我知道如果状态或道具发生了变化,组件将重新渲染,但是我觉得我正在进行一些不必要的渲染,我不确定如何跟踪它,或者不确定它是否开始。

我有一个博客列表,其中包含4个帖子,这些帖子是从api提取后在useEffect中设置的时间轴原子映射的。 <Post/>组件每次刷新刷新17次。我不应该期望它只能渲染4次吗?

这是应用程序的基本结构:

<UserProvider>
  <App>
    <Application>
      <Timeline> // fetch post data in useEffect w/ cleanup, then (items) => setTimeline(items)
        {timeline && timeline.map((post, i) => {
          <Post data={post} key={i}/> // there are 4 posts in the db
        } 
      </Timeline>
    </Application>
  </App>;
</UserProvider>

以下指示页面刷新后的呈现顺序。我将console.log放在每个组件的return之前。

<APP /> // renders only once (so far so good...)
<APPLICATION /> // Application renders 4 times
<TIMELINE /> // Timeline renders 9 times
<APPLICATION />
<TIMELINE />
<APPLICATION />
<TIMELINE />
<TIMELINE />
<APPLICATION />
<TIMELINE />
<TIMELINE />
<TIMELINE />
<POST /> // Post renders 17 times (there are only 4 posts)
<POST />
<POST />
<POST />
<POST />
<POST />
<POST />
<POST />
<TIMELINE />
<POST />
<POST />
<POST />
<POST />
<POST />
<TIMELINE />
<POST />
<POST />
<POST />
<POST />

0 个答案:

没有答案