Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

javascript - How to avoid re-rendering the whole List instead of adding the new item to the DOM list in react JS?

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.

enter image description here

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".

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>
  ); 
}

Read more in React's Dynamic Children doc section.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...