table 中的每条记录都应该有一个唯一的 `key` 属性,或者将 `rowKey` 设置为一个唯一的主键

Each record in table should have a unique `key` prop,or set `rowKey` to an unique primary key

我正在用 ant design 渲染一个 table,它工作正常,但控制台中有一个警告:

Each record in table should have a unique key prop,or set rowKey to an unique primary key

我的代码如下:

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;

React 使用 key 属性渲染列表。它之所以有效,是因为 React 允许您降低差异算法的复杂性并减少 DOM 突变的数量。您可以在 React Reconciliation 文档中阅读更多内容:https://reactjs.org/docs/reconciliation.html

在您的例子中,您将键添加到列,而不是行。将键字段添加到数据源。因此您的代码可能如下所示:

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 => ({
                    key: row.id, // I added this line
                    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;

因为您没有将键添加到 dataSource 数组,所以还要在其中添加一个键。

像这样:

const results= responseJson.map(row => ({

    key: row.ClientId,     // here

    ClientId: row.ClientId,
    ClientSecret: row.ClientSecret,
    Id: row.Id,
    SiteCollectionTestUrl: row.SiteCollectionTestUrl,
    TenantDomainUrl: row.TenantDomainUrl
}))

或者您可以使用 属性 rowKey 将 dataSource 数组的任何唯一值用作键,如下所示:

<Table
   columns={columns}
   dataSource={this.state.data}

   rowKey="Id" />     // any unique value

Doc Reference.

只需在标签中添加唯一键值 link this:

   <Table
   columns={columns}
   dataSource={this.state.data} 
   rowKey="Id" />  // unique key

希望对您有所帮助

React Table 唯一键/行键

Each record in table should have a unique key prop,or set rowKey to an unique primary key.

解决方案 1

each col has a unique key

// each column with unique key

import React from 'react';

import {
  Table,
} from 'antd';

const leftTableColumns = [
  {
    title: 'Page / Modal',
    dataIndex: 'pageModal',
    key: 'pageModal',
  },
  {
    title: 'Success Rate',
    dataIndex: 'successRate',
    key: 'successRate',
  },
];

const LeftTable = (props) => {
  const {
    leftTableDatas,
  } = props;
  return (
    <>
      <Table
        columns={leftTableColumns}
        dataSource={leftTableDatas}
      />
    </>
  );
};

export {
  LeftTable,
};

export default LeftTable;


解决方案 2

only need set rowkey on the table with the unique value

// table with rowkey

import React from 'react';

import {
  Table,
} from 'antd';

const leftTableColumns = [
  {
    title: 'Page / Modal',
    dataIndex: 'pageModal',
  },
  {
    title: 'Success Rate',
    dataIndex: 'successRate',
  },
];

const LeftTable = (props) => {
  const {
    leftTableDatas,
  } = props;
  return (
    <>
      <Table
        // shorthand rowKey
        rowKey="id"
        // rowKey={obj => obj.id}
        columns={leftTableColumns}
        dataSource={leftTableDatas}
      />
    </>
  );
};

export {
  LeftTable,
};

export default LeftTable;


参考

https://ant.design/components/table/

只有您需要在 table 上设置具有唯一值的 rowkey


 <Table
  dataSource={[finance]}
  columns={columns}
  rowKey={record => record.id}
 />

我用这个解决方案

rowKey="{record => record.id}"

rowKey="id"

但在您的集合中必须存在 id 列

快速破解

我确实分配随机数学数字更改为每个键上的字符串。?

也就是说我的专栏变成了

const columns = [
            {
                title: 'Client Id',
                dataIndex: 'ClientId',
                key: () => Math.random().toString(),
            }, 
            {
                title: 'Site Collection TestUrl',
                dataIndex: 'SiteCollectionTestUrl',
                key: () => Math.random().toString(),
            },
            {
                title: 'Tenant DomainUrl',
                dataIndex: 'TenantDomainUrl',
                key: () => Math.random().toString(),
            }
    ];

希望这对未来来访的人有所帮助......

我遇到了你的问题,这个方法回答了

<Table 
  columns={columns} 
  dataSource={data} 
  rowKey="name" 
/>

我遇到了同样的问题,但已解决,希望对您有所帮助:) 只需添加 rowKey='id' 我使用 rowKey = 'id' 因为 'id' 是变量数据源中的唯一数据,但您可以使用变量数据源中的另一个唯一值。 (具有唯一值)

import React from 'react'
import { Table } from 'antd' 

const committeInformation = () => {

 const columns = [
  {
    key: '0',
    title: 'id',
    dataIndex: 'id',
  },
  {
    key: '1',
    title: 'name',
    dataIndex: 'name',
  },
  {
   key: '2',
   title: 'email',
   dataIndex: 'email'
  }
 ]

 const dataSource = [
   {
     id: '1',
     name: 'user 1',
     email: 'coco@gmail.com',
     
   },
   {
     id: '2',
     name: 'user 2',
     email: 'coco@gmail.com'
    }
  ]

  return (
    <Table
     rowKey='id' //this from variable dataSource
     columns={columns}
     dataSource={dataSource}
    />
  )
}

 export default committeInformation