The original link
Today we discuss a question that we often encounter in front-end interviews. What’s wrong with using index as the key? We often deal with key values in our daily development. But we ask ourselves, do we really understand Key? I think most of my friends might be a little hesitant.
For starters, it may be difficult to understand the meaning of a key value. We can think of it simply as a unique identifier for each piece of data. It’s associated with this piece of data. It’s enough to understand this place.
So why not use index as the key?
As shown in the figure:
For the list above, we use index as the key. The corresponding relationship is shown in the figure
The page displays without problem and the console does not report errors.
but
Suppose we delete item 2 from the List at this point (the virtual DOM is easy). Let’s see what happens, okay?
Can you see what happens to both lists?
Let’s take a closer look:
When we delete the subscript 1 from the original list (after the virtual DOM is easy). You can see that the indices of all the data have changed except for the first index
The question then arises:
Among the original data:
- Diff algorithm is easy to understand – > 2
- Text is no trouble -> 3
- Easier to understand -> 4
They use subscripts as key values, which change as the page is rerendered
- Diff algorithm is easy to understand – > 1
- Text narration is no trouble -> 2
- It’s easier to understand -> 3
The problem is that the previous data and the re-rendered data change with the key value and cannot be associated. That would lose the point of the key. It is also the culprit that causes the data to appear strange!
During development, because most of our data comes from the background. Each piece of data in the database is uniquely identified by an ID. This id is also the most commonly used source of key values
The negative Side of using an index as a key
A final note: avoid using itindex
As akey
It’s worth the coding habit. Remember! Remember that!