One 、 written words
key Give Way React know , Currently newly generated React The elements of the elements , Whether it can be generated before React Find the corresponding in the element . If there is , Then just take it and use it . Suppose you insert an entry at the head of the list , By comparison ,React Know that the items have not changed except for the head .React Yes DOM During operation , Just insert a node in the head . The rest of the nodes don't move them .
If developer No settings key, that React Will set it up key Is the index value of the item in the list . Suppose the head inserts an item , Two React A comparison of trees ,React Look at your first element and the previous one key equally , It's just props Changed the （ Here we assume that the contents of each item in the list are different ）. That only needs to be done for the first DOM Node update . Compare the second element ,React Look, you're the same as the second element before , It's just props Changed the , That only needs to be done for the second one DOM Node update . Compare the third element ,React Look, you're the same as the third element before , It's just props Changed the , That only needs to be done to the third one DOM Node update ... Finally, there is an extra element left ,React Take a look at your key I haven't seen it before , Create a new one DOM Nodes are inserted into the above DOM The end of the nodes .
In conclusion ： If the original list had n term . Developer settings key The overhead of value is to create a DOM Node overhead .
Developers don't set key The overhead of value is to create a DOM Node overhead and update n Cost of nodes .
Two 、 Code
For a better understanding of key The role of , You can click the link to see the code and page effect .
Reference material ：
 Understand the virtual DOM And key The function of attributes .https://time.geekbang.org/course/detail/100009301-9441
 Coordinate .https://zh-hans.reactjs.org/docs/reconciliation.html