gpt4 book ai didi

javascript - 警告 : Each child in an array or iterator should have a unique "key" prop. key 已存在

转载 作者:行者123 更新时间:2023-11-30 14:27:11 25 4
gpt4 key购买 nike

我有一个 React 组件,它接受一个数组并使用预定义键将其呈现为表格。

<TableFromJson data={this.props.results.events} rowKey="eventID" />

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
}

这会呈现如下所示的表格:

Component with key shown in React Dev Tools

tr 元素已经包含 key ,正如您从上面 React Dev 工具的屏幕截图中看到的那样。

每次呈现此组件时,我都会收到关键错误(“警告:数组或迭代器中的每个子项都应该有一个唯一的“关键” Prop ”)。我错过了什么?

最佳答案

您还应该向子元素添加键:thtd,就像您已经为 tr 所做的那样。

关于javascript - 警告 : Each child in an array or iterator should have a unique "key" prop. key 已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51750101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com