Problem analysis

  • Most children will have seen this Warning when using React, especially when iterating over render elements

index.js:1446 Warning: Each child in a list should have a unique "key" prop.

  • So I’m used to assigning an itemkey, and sometimes we will specify the index of the list directly for conveniencekeyBut it’s not recommended, so why?

warren

React performs the following steps:

  • Use the state and JSX template to generate the virtual DOM, and then use the virtual DOM to generate the real DOM. When the state changes, the render function executes to generate the new virtual DOM, and then compares the differences between the old and new virtual DOM, find the differences, and then directly manipulate the DOM to change the different content. This greatly improves performance over traditional DOM manipulation.

  • The core of the virtual DOM is the React diff algorithm. To understand this problem, we should first look at the DIff algorithm

As can be seen from the figure above, React updates the virtual DOM layer by layer. In other words, there are differences in the first div layer. After comparison, update the corresponding current node in the real DOM directly, and so on.

Solve the problem

  • Good! Now we can look at thiskeyIf we have A list [A,B,C] in state and use the index as the key when traversing the render, then this looks like this.
A 0
B 1
C 2
Copy the code

If we perform an operation to delete a from the array, our list will be [b, C], and we will still use the index as the key when traversing the render, resulting in the following:

As shown in the figure, if we do not use the key index, the program can quickly compare the difference, and vice versa, but must compare the entire virtual DOM, so that the program can still run normally, but greatly consumes the performance of the comparison between the old and new virtual DOM, and may cause component status problems.

  • So, set the index to key, ok?You can, but this is not recommended, as it can significantly consume the performance of the virtual DOM