我正在用 ant design 渲染一个表格,它工作正常,但控制台中有一个警告:
表中的每条记录都应该有一个唯一的
key
,或者将rowKey
设置为唯一的主键
我的代码如下:
import React, { Component } from 'react';
import { Table} from 'antd';
import { adalApiFetch } from '../../adalConfig';
class ListTenants extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
fetchData = () => {
adalApiFetch(fetch, "/Tenant", {})
.then(response => response.json())
.then(responseJson => {
if (!this.isCancelled) {
const results= responseJson.map(row => ({
ClientId: row.ClientId,
ClientSecret: row.ClientSecret,
Id: row.Id,
SiteCollectionTestUrl: row.SiteCollectionTestUrl,
TenantDomainUrl: row.TenantDomainUrl
}))
this.setState({ data: results });
}
})
.catch(error => {
console.error(error);
});
};
componentDidMount(){
this.fetchData();
}
render() {
const columns = [
{
title: 'Client Id',
dataIndex: 'ClientId',
key: 'ClientId'
},
{
title: 'Site Collection TestUrl',
dataIndex: 'SiteCollectionTestUrl',
key: 'SiteCollectionTestUrl',
},
{
title: 'Tenant DomainUrl',
dataIndex: 'TenantDomainUrl',
key: 'TenantDomainUrl',
}
];
return (
<Table columns={columns} dataSource={this.state.data} />
);
}
}
export default ListTenants;
原文由 Luis Valencia 发布,翻译遵循 CC BY-SA 4.0 许可协议
React 使用 key 属性渲染列表。之所以如此,是因为 react 允许您降低差异算法的复杂性并减少 DOM 突变的数量。您可以在反应协调文档中阅读更多内容: https ://reactjs.org/docs/reconciliation.html
在您的情况下,您将键添加到列,但没有添加到行。将关键字段添加到数据源。所以你的代码可能如下: