[英]Warning: Each child in an array or iterator should have a unique “key” prop. Keys are already present
I have a React component that accepts an array and renders it as a table using a predefined key. 我有一个React组件,它接受一个数组,并使用预定义的键将其呈现为表。
<TableFromJson data={this.props.results.events} rowKey="eventID" />
TableFromJson.js TableFromJson.js
import React, { Component } from 'react';
import { Table } from 'react-bootstrap';
import PropTypes from 'prop-types';
export class TableFromJson extends Component{
render() {
if (!this.props.data)
return(<p>No data</p>);
const key = this.props.rowKey;
let columns = Object.keys(this.props.data[0]);
let headerComponents = columns.map(col => <th>{col}</th>);
let rowComponents = this.props.data.map((row) =>{
let tdList = columns.map(col => <td>{row[col]}</td>);
let htmlRow = <tr key={row[key]}>{tdList}</tr>;
return htmlRow;
});
return (
<Table bordered hover responsive striped>
<thead>
<tr>{headerComponents}</tr>
</thead>
<tbody>{rowComponents}</tbody>
</Table>
);
}
}
TableFromJson.propTypes = {
data: PropTypes.array,
key: PropTypes.string
}
This renders a table as show below: 这将显示一个表格,如下所示:
The tr element already contains the key as you can see from the above screenshot from React Dev tools. 从上面的React Dev工具截图中可以看到,tr元素已经包含了密钥。
I'm getting the key error ("Warning: Each child in an array or iterator should have a unique "key" prop") every time this component is rendered. 每次呈现此组件时,都会出现关键错误(“警告:数组或迭代器中的每个子代都应具有唯一的“关键”道具”)。 What am I missing?
我想念什么?
您还应该向子元素添加键: th
, td
,正如您已经为tr
所做的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.