【发布时间】:2020-08-28 06:27:23
【问题描述】:
我正在生成一个 TSX 元素列表:
this.productsModel = this.state.products.map(o => (
<Grid.Column key>
但是,react 警告我:
警告:列表中的每个孩子都应该有一个唯一的“key”属性。
所以按照推荐的做法 [1] 我补充说:
this.productsModel = this.state.products.map((o, i) => (
<Grid.Column key={i}>
但key={i} 在渲染时被剥离,无论元素是什么(Grid.Column、div 等)。
怎么会?如何解决?
【问题讨论】:
-
请仔细阅读文档。 React 不推荐使用
index作为 keyWe don’t recommend using indexes for keys if the order of items may change -
正如@prasanth 所说,react 不建议对键使用索引。 here are the official docs of keys and indexes 和 here is the post react 建议更好地解释它
-
其实这不是问题,因为我没有生成元素。元素的定义和排序都很好,可以从数据库中获取。
标签: javascript reactjs