reactjs - 数组或迭代器中的每个孩子都应该有一个唯一的“key”道具。不知道为什么
问题描述
const list = props.things.toDo.map(
function(thing) {
return(
<li>{thing.name}</li>
);
}
);
无法解决这个问题,继续收到这个反应警告?!
解决方案
键帮助 React 识别哪些项目已更改、添加或删除。应为数组内的元素提供键,以使元素具有稳定的标识:
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
选择键的最佳方法是使用一个字符串,该字符串在其兄弟项中唯一标识一个列表项。大多数情况下,您会使用数据中的 ID 作为键:
const list = props.things.toDo.map(
function(thing) {
return(
<li key={thing.id}>{thing.name}</li>
);
}
);
当您没有渲染项目的稳定 ID 时,您可以使用项目索引作为键作为最后的手段:
const list = props.things.toDo.map(
function(thing, index) {
return(
<li key={index}>{thing.name}</li>
);
}
);
如果项目的顺序可能发生变化,我们不建议对键使用索引。这会对性能产生负面影响,并可能导致组件状态出现问题。如果您选择不为列表项分配显式键,那么 React 将默认使用索引作为键。
推荐阅读
- sql - SQL 循环。我想遍历一个包含 SELECT 结果的循环
- c# - .NET Core 2.1 Web Scraper 控制台输出“HtmlAgilityPack.HtmlDocument
- git - 定期从大型 svn 存储库更新 git 存储库 - git svn fetch 和 git svn rebase 有何不同?
- javascript - 使用导航箭头时,图表 JS 图表未在 ArcGIS 弹出窗口中呈现
- dart - 使用列时如何在步进器中使用扩展
- sql-server - SQL Server 合并和 pk 冲突
- excel - 使用 powershell 创建监视文件夹以更改加载到其中的多个 Excel 工作表中的特定列(从一般到最新)
- java - 复制公式 POI 的单元格值
- python - 使用默认值验证 django 中的表单字段
- python - 如何在 Packrat 环境中使用 rpy2?