Ant Design Table组件key值报错

4,078 阅读1分钟

在使用Ant Design for React对接数据时发现控制台报错如下:

Each child in a list should have a unique "key" prop.

或者

Warning: [antd: Table] Each record in dataSource of table should have a unique `key` prop, or set `rowKey` of Table to an unique primary key, see https://u.ant.design/table-row-key 

方法解决:

<Table columns={columns} dataSource={list}  rowKey="id" pagination={false} bordered />

注意:此处的rowKey必须是一个list返回的唯一值,可以是id,也可以是其他的自定义字段。

封装的table 表格
import React from 'react'
import Table from 'antd/lib/table'
import './index.scss'
export default function LzcTable(props) {
    const {style,tableClass,rowSelection,columns,dataSource,loading,onMouseDownHandle,emptyTxt,scroll,scrollHandle,rowClassName} = props
    return (
        <div className={`lzc-table ${tableClass}`} style={style} onScrollCapture={scrollHandle}>
            <Table
                rowSelection={rowSelection}
                columns={columns}
                dataSource={dataSource}
                rowKey={(record: any) => record[rowKey]}
                locale={{
                    emptyText: emptyTxt
                }}
                pagination={false}
                loading={{
                    tip:"数据加载中...",
                    // indicator:<div>loading...</div>,
                    spinning:loading,
                    wrapperClassName:'tableLoading'
                }}
                onRow={(record)=>{
                    return {
                        onMouseDown: (e)=>{onMouseDownHandle&&onMouseDownHandle(e,record)}
                    }
                }}
                scroll={scroll}
                rowClassName={rowClassName}
                expandIconAsCell={false}
                expandIconColumnIndex={-1}
            />
        </div>

    )

}

LzcTable.defaultProps={
    emptyTxt:'没有搜索到结果!',
    tableClass: '',
    style: {},
    rowKey: 'id',
}

// rowSelection 是否可以选择行
// columns 行数据
// dataSource 元数据
// loading 加载状态