![](/img/trans.png)
[英]Warning: Each child in a list should have a unique "key" prop. Check the render method of `RenderComments`
[英]Unique “key” prop warning in render method - ReactJS
我的应用程序有一个警告说: Each child in an array or iterator should have a unique "key" prop. Check the render method of 'SortableTable'
Each child in an array or iterator should have a unique "key" prop. Check the render method of 'SortableTable'
听说是我的SortableTable文件:
import React from 'react';
import {Link} from 'react-router';
import {v4 as uuid} from 'node-uuid';
export default class SortableTable extends React.Component {
render() {
return (
<table style={{width: '100%'}} className={this.props.className} id={this.props.id}>
<thead>
<tr>
{this.props.headers.map(this.generateHeaders)}
</tr>
</thead>
<tbody>
{this.props.children}
</tbody>
</table>
);
}
generateHeaders = (value) => {
if (Object.keys(value).length === 0) return
let sort, colspan
if(value.sort) {
let {query} = this.props;
let nQuery, title, icon, colspan = 1;
if(query.sort === value.sort && query.sortDirection === 'desc') {
nQuery = Object.assign({}, query, {sort: value.sort, sortDirection: 'asc', page: 1})
title = 'asc';
icon = String.fromCharCode(0xe630)
} else {
nQuery = Object.assign({}, query, {sort: value.sort, sortDirection: 'desc', page: 1})
title = 'desc';
icon = String.fromCharCode(0xe62d)
}
sort = <Link to={this.props.link} query={nQuery} className="icon order active" title={title} data-icon={icon} />
}
let className = value.className ? value.className : ''
if(value.colspan) {
colspan = value.colspan
}
return <th className={className} colSpan={colspan}><span>{value.name}</span>{sort}</th>
}
有人可以告诉我如何设置关键道具来解决此警告吗?
想法是拥有一个具有唯一值的键属性。 您可以使用index,即Array#map
回调的第二个参数 :
generateHeaders = (value, index) => {
// ...
return <th key={index} className={className} colSpan={colspan}><span>{value.name}</span>{sort}</th>
}
或者,如果value
对象具有唯一的属性(如id
,则可以使用它。
generateHeaders
返回的<th>
元素需要设置一个key
属性,因为您要从render
方法返回它们的数组。
实现此目的的最简单方法是使用索引:
generateHeaders = (value, index) => {
// ...
return <th key={index} //...
这将使警告消失,但是最好使用每个value
的唯一属性(如果存在)。 这是因为React使用该键来确定两个项目是否相同。 如果使用数组索引,并且在数组中的某个位置插入新值,则索引将更改,从而导致不必要地重新渲染项目。
您应该将密钥插入标签:
generateHeaders = (value, index) => { ... return <th key={index} className={className} colSpan={colspan}><span>{value.name}</span>{sort}</th> }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.