如何避免重新呈现整个List而不是将新项添加到react JS中的DOM列表? [英] How to avoid re-rendering the whole List instead of adding the new item to the DOM list in react JS?

查看:93
本文介绍了如何避免重新呈现整个List而不是将新项添加到react JS中的DOM列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与React演示和其他示例一样,如果添加或删除了一条记录,我会看到人们重置状态数据。这导致整个列表被重新渲染,而不是简单地追加最新记录,或者从当前DOM树中删除所选择的记录。

As in the React demo, and other examples, I see people resetting the State data if one record is added or removed. Which results in the whole list being re-rendered instead of simply appending the latest record, or removing the selected one from the current DOM tree.

它有什么用?或者我该如何避免这种情况。

How is it helpful? Or how can I avoid this case.

更新
情况:Facebook Feed,您不断滚动Feed,达到约5000个Feed状态和许多其他类型的卡片。不仅如此,每个状态Feed都有自己的评论列表。

UPDATE The situation: Facebook feed, you keep scrolling the feed, reach around 5000 feed statuses and many other types of cards. Not just that, each status feed has it's own "comment list".

每秒,5-10张状态卡预先挂在墙上,或附在案例中延迟加载。即。每一秒,你重新渲染n + n * 0.5,其中n可以超过5000张卡。

Every second, 5-10 status cards are pre-pended to your wall, or appended in case of lazy loading. ie. every second, you re-render n+n*0.5, where say n can go above 5000 cards.

另外,请考虑重新绘制的成本,渲染循环。

Also, do consider the cost of "repainting", rendering loops.

推荐答案

如果你给列表中的每个项目一个唯一的(和确定的) key = uniqueValue prop,然后React将保留密钥未更改的列表项,从而避免重新呈现整个列表。

If you give each item in the list a unique (and deterministic) key=uniqueValue prop, then React will preserve list items where the key has not changed, thus avoiding a re-render of the entire list.

render() {
  var comments = comments.map(function(comment){
    return (
      <Comment
        key={comment.id} // This should be a unique, deterministic value
        ...
      />
    );
  });

  return(
    <div>
      {comments}
    </div>
  ); 
}

在React的 Dynamic Children doc section。

Read more in React's Dynamic Children doc section.

这篇关于如何避免重新呈现整个List而不是将新项添加到react JS中的DOM列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆