4 ms·
I'm seeing a lot of bad solutions to this problem written in response to you, so let me say "Do not ignore the the console warnings about array item keys" and l
by feedjoelpie 11y ago
I'm seeing a lot of bad solutions to this problem written in response to you, so let me say "Do not ignore the the console warnings about array item keys" and list out some gotchas:
* Supply the key to the top level list item component. Do NOT have the list item component define its own key in its render method. That is not how it works
* Don't use the array index for the key. Use something that's unique to the VALUE.
* Don't use _.uniqueId() or similar in any render loop. It will trigger a re-render every time, even if your underlying data has not changed.
* If you use _.uniqueId() outside of a render loop, for example to set a temp ID on a brand new data model (what Backbone does by default), and you have an isomorphic setup, make sure that your client and server counters stay in sync. The server version of _.uniqueId() will just keep counting up forever unless you do something about it.
You really need to try to find something unique (or unique enough) about the data itself. In the case of strings, use the string as the key. If the case of objects, if you really HAVE to, if there is nothing else that could possibly work right, you might get desperate and JSON.stringify them to make the key. Hopefully it doesn't come to that but it's still often better than alternatives that force full DOM reconciliation on the whole list.
- ConAntonakos 11y agoShit. I've been using uniqueId from Lodash b/c I wasn't sure what was a better solution. What if it's a static, non-DB-fetched array? Would array indices still not suffice?
- raquo 11y agoIf the array does not change over time, using array indices is perfectly fine. You can use anything as a key as long as you guarantee that it stays the same for that specific element. If you don't change or reorder the array, the element's index does give such a guarantee.