sam*_*cow 5 javascript reactjs
我了解使用Components数组时,键属性假定为数组的索引,应明确设置。是否建议明确规定这些孩子的孩子?
{arr.map(item, i) => {
<Parent
key={item.ID}
>
<Child
key={`child${item.ID`} //required to ensure correct reconciliation?
/>
</Parent>
}
Run Code Online (Sandbox Code Playgroud)
键帮助 React 识别哪些项目已更改、添加或删除。应为数组内的元素提供键,以赋予元素一个稳定的身份(来源)
The general purpose of a key is to optimize React's rendering performance. If you have a list of items, giving a key tells React how to remember this item for subsequent renders. If you use an array index, that can defeat the purpose of the key (if the order of those elements change). Its better to use a unique ID or something more specific to the entity being rendered.
With that context, The parent element is what needs the key, so React can do its optimizations. The children of that "dynamic" element are attached to that parent / its key so there's no need to apply a key on the children`. Just the parents that are rendered in a loop :)
| 归档时间: |
|
| 查看次数: |
46 次 |
| 最近记录: |