为什么列表项在反应中需要唯一键,而其他项不需要?
Why list items need unique key, but other not, in react?
为什么渲染列表项需要传递 key 属性而其他元素不需要?
例如,如果我喜欢 -
['apple', 'orange', 'lemon'].map((fruit, i) => {
return <li key={i}>{fruit}</li>;
});
前面的代码片段需要传递 key={i}
道具,但是如果我做同样的工作,比如 -
<ul>
<li>apple</li>
<li>orange</li>
<li>lemon</li>
</ul>
在这种情况下,我们不需要使用 key
属性。
所以,问题是为什么我们在第一种情况下需要 key prop 而在第二种情况下为什么不需要?
React 官方文档在其他地方讨论了键 here。这是关键(没有双关语意)引述:
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity
当你渲染一个元素数组时,这个数组可能会改变,或者数组中的元素可能会改变,提供一个 key
可以帮助 React 确定应该更新数组中的哪个元素.当 React 对应该更新哪个元素感到困惑时,不提供 key
可能会引入错误。
你的第二个例子不需要 key
因为什么都没有改变——它只是几个静态元素,所以没有 React 对更新什么感到困惑的风险。
为什么渲染列表项需要传递 key 属性而其他元素不需要?
例如,如果我喜欢 -
['apple', 'orange', 'lemon'].map((fruit, i) => {
return <li key={i}>{fruit}</li>;
});
前面的代码片段需要传递 key={i}
道具,但是如果我做同样的工作,比如 -
<ul>
<li>apple</li>
<li>orange</li>
<li>lemon</li>
</ul>
在这种情况下,我们不需要使用 key
属性。
所以,问题是为什么我们在第一种情况下需要 key prop 而在第二种情况下为什么不需要?
React 官方文档在其他地方讨论了键 here。这是关键(没有双关语意)引述:
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity
当你渲染一个元素数组时,这个数组可能会改变,或者数组中的元素可能会改变,提供一个 key
可以帮助 React 确定应该更新数组中的哪个元素.当 React 对应该更新哪个元素感到困惑时,不提供 key
可能会引入错误。
你的第二个例子不需要 key
因为什么都没有改变——它只是几个静态元素,所以没有 React 对更新什么感到困惑的风险。