Diff algorithm in Vue and React

We hear about the virtual DOM a lot in VUE and React, so what does it do? Today I’m going to use key to explain this thing! There is no code today, but there are code blocks haha

When we do array traversal, we usually need to bind a key value, otherwise we will get an error, such as <ul><li v-for="(item,index) in arr" :key="index">{{item.label}}</li>
</ul>
Copy the code

Above we iterate through an array and use index as our key. The code works, but there are some unexpected problems. First of all, our diff algorithm compares the virtual DOM and the real DOM by the key value. When the key value is unchanged, no new real DOM is generated. That is why we use this key, because it allows us to reuse the original DOM in place and does not need to generate a new real DOM.

Did you notice that the key I’m using is index, and there’s a problem with index, and that’s when I’m nesting a label inside the node, and if I add a node element to the array, there’s a problem, and you can guess what the problem is. Because the diff algorithm compares each node by key, including the elements nested below the node, when your key changes but the elements nested below the key do not change, then a bug occurs. You can try it.

Second, solutions

We can use the unique value of the element as the key, such as id, etc., because this is a unique value, so diff will not find the wrong value every time