我不明白教程中的这一部分:https : //svelte.dev/tutorial/keyed-each-blocks。
我可以看到things数组已正确更新,因此thing.color按预期传递了权利。但是从第一句“默认情况下,当你修改一个each块的值时,它会在块的末尾添加和删除项目,并更新任何更改过的值。”,似乎是在说 Svelte 无论如何都会删除单击按钮时最后一个块,则剩余的 4 个块将面临切片things,即
[{ id: 2, color: '#6a00a8' },
{ id: 3, color: '#b12a90' },
{ id: 4, color: '#e16462' },
{ id: 5, color: '#fca636' }]
Run Code Online (Sandbox Code Playgroud)
并且由于initial声明为const,因此无法再更新,因此thing.id1--4的颜色保留。
这是正确的理解吗?假设each块是可交换的,这是默认行为吗?
然后它说使用thing.id作为each块的键将解决问题,即{#each things as thing (thing.id)}. 我不明白如何在each块中使用密钥以及如果thing.id未提供默认密钥是什么。以及为什么默认键(如果有,或者默认无键)在提供时thing.id不起作用。
感谢您的澄清。
Uma*_*iya 11
I believe it uses something like the index of the item as the default when you do not provide a key. This can be validated by using
{#each things as thing, index (index)}
<Thing current={thing.color}/>
{/each}
Run Code Online (Sandbox Code Playgroud)
which gives the same behavior as not using a key in the first place.
Let's call the <Thing> that was rendered for id: 1 as Thing1, and so on.
When we remove the first item from the list, Thing1 still stays the same, because the key (index in this case) associated with it remains the same. The prop that was earlier being sent to Thing2 is now being sent to Thing1. This happens all the way down the chain. But now that there is one less element, Thing5 is removed from the DOM.
The instance of the component Thing that is associated with the key "0" (Thing1) is not destroyed when the first item is removed. This happens because the key stays the same (the new array also has an item at index 0). Only the prop that is being sent to Thing1 has changed, leaving the initial variable with the color of the original item with id: 1.
When the thing with id: 1 is removed, there does not exist any instance of Thing which maps to "1". So, Thing1 is removed from the DOM.
Another way to understand is when you give a key, you are essentially telling Svelte to map each rendered block to that very key. When that key doesn't exist anymore, get rid of the block and remove it from the DOM. But if the key stays the same and the props change, update the props instead of recreating the block.
When you don't specify a key, it uses the index of the list as the key. So if you remove items from the list, it won't recreate or reorder the block, it will just update the props.
| 归档时间: |
|
| 查看次数: |
1851 次 |
| 最近记录: |