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

前端 未结 1 1103
孤城傲影
孤城傲影 2020-12-16 04:32

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

相关标签:
1条回答
  • 2020-12-16 05:13

    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.

    0 讨论(0)
提交回复
热议问题