Each element in list must have a unic key. So how can create this key?
I did function which return keys like this:
- QV8938
- XN0210
- DC7389
- DC8376
- HA8357 etc. With random. Is it normal to create such keys?
CodePudding user response:
Is it normal to create such keys?
No, and it's not a good idea. Read the Lists and Keys documentation.
There are three separate problems with random keys:
If they're random, you might end up with the same key on more than one item. (You can mitigate this problem with a sufficiently-powerful random generator like ones used for GUIDs, though.)
You'll cause unnecessary work committing to the DOM for something that hasn't actually changed when its key changes.
You'll cause display errors by not re-committing to the DOM when something does change but its key doesn't change.
Instead, derive your keys from the data for the items being displayed, which is always possible, even if it means you have to create artificial keys for them and then reuse those artificial keys.
You might be tempted to use array indexes as keys. That's not a good idea either in almost any case (that post is linked from the documentation above). The only exception is a static array of static items — nothing in it is ever modified, nor does its order ever change; in that one case, using the index as a key is okay.