In the virtual DOM, why can't we use index instead of key?

Reference: easily understand why Index is not used as the key

Whether it is vue or react, the virtual DOM mechanism is used to update the real DOM in the browser.
Take ul> li *5 as an example, click each li from top to bottom to delete; the diff algorithm compares newVDom with oldVDom, finds li tags with the same key value, and compares them one by one from top to bottom.
Originally, we only need to delete the first li node in the list one by one for each click. **If index is used as the key value, the key of li in the newly generated newVDOM will be dynamically assigned after each click event, resulting in comparison. Misplacement makes diff think that every li has changed, **So every time a li is deleted, the page will re-render all the list items.
If each item has a unique key instead of a subscript , every time you click, enter The diff algorithm compares the old and new VDOMs to get the result: only a node is deleted, and the newVDOM is mapped to the real DOM. Only one operation is performed to delete the dom, and other li is not re-rendered, which greatly improves performance.

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108288563