The answer should be logical, starting from the perspective of react rendering design idea, the problems faced, the principle of diff algorithm, the problems and possible solutions
React adopts the idea of virtual DOM. When re-rendering is needed, snapshots of the old and new DOM numbers are compared to find out the changed parts, so as to minimize DOM changes and convert one tree structure into another. Usually the algorithm complexity is On3. Then the algorithm is optimized by combining with the features of the front-end usage scenarios
- The preferred front end has few nodes moving across hierarchies
- Having components of the same type produces similar structures
- For nodes at the same level, they can be distinguished by unique ids
The first step is to compare each layer (via updateDepth control), and if the same layer finds a difference, destroy the node and all nodes below it, even if its children are reusable
Diff then provides insert, delete, and move operations in a hierarchical comparison based on the unique ID of the label type or key attribute of the component. The unique key can be used to determine whether the new and old sets have the same node. If the same node exists, the new snapshot node index is compared with the old snapshot node index, and the new snapshot node index is greater than the old snapshot node index. Imagine playing poker in one direction like J,K,Q, A -> J,Q,K,A just move the K behind the Q to become A dragon (I guess their inspiration came from poker HH).
But there is a problem with this one direction algorithm, if you move the last node to the first node, but you move the previous nodes behind the last node. So avoid this scenario
I suspect that in the future, two-way diff will be added if this scenario needs to be resolved