【问题标题】:How to remove following unique key issue如何删除以下唯一密钥问题
【发布时间】:2020-06-30 05:08:47
【问题描述】:

这里我使用的是 react js 的 ANT 表组件。当我单击链接并转到我正在使用 ANT Table 组件的相关页面时,“列表中的每个孩子都应该有一个唯一的“关键”道具。”每次都会重现此错误。检查我的以下代码。我想在这里添加什么?请查看我的代码并告诉我。

     <Table dataSource={state.cardsList}>
        <Column
          title="Credit card number"
          dataIndex="cardNumber"
          key="cardNumber"
        />
        <Column
          title="Expiry month"
          dataIndex="expMonth"
          key="expMonth"
        />
        <Column title="Expiry year" dataIndex="expYear" key="expYear" />
        <Column
          title="Action"
          key="action"
          dataIndex="action"
          render={(text, record) => (
            <Space size="middle">
              {/* <a>Invite {record.lastName}</a> */}
              <a onClick={() => removeCard(record)}>Delete</a>
            </Space>
          )}
        />
      </Table>

非常感谢您。

【问题讨论】:

  • 为什么要创建列而不是使用columns={columns} 属性?
  • reactjs.org/docs/lists-and-keys.html 可以帮助您了解这一点。你能分享一下你的数据形状是什么样的吗? IE。 it 是否在每个对象上定义了一个关键属性。它在数据集中是唯一的吗?
  • 您可以在 Table 标签上使用 rowKey 属性并将对象的唯一键分配给它。例如
  • 在您的情况下,对于所有记录,您将拥有与第一列的“cardNumber”相同的键。其他两列也是如此。键必须是唯一的。
  • 谢谢你们宝贵的cmets。

标签: reactjs error-handling syntax-error antd


【解决方案1】:

您的dataSource 中似乎没有唯一的key 属性。

确保state.cardsList 中的每个元素都有一个key 属性,如下所示:

const dataSource = [
  {
    key: '1',    // unique key property
    name: 'Mike',
    age: 32,
    address: '10 Downing Street',
  },
  {
    key: '2',   // unique key property
    name: 'John',
    age: 42,
    address: '10 Downing Street',
  },
  ...
];

如果您的 state.cardsList 没有唯一键,则只需映射它并添加键:

<Table dataSource={state.cardsList.map((el, idx) => ({key: idx, ...el}))}>
...

希望对你有帮助。

【讨论】:

    【解决方案2】:

    您现有的数据通常已经有一些独特的东西可以用作key(不必命名为key)。

    只需在创建&lt;Table&gt; 时设置rowKey:

    <Table dataSource={state.cardsList} rowKey="id">
    

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 2012-02-06
      • 2013-02-19
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多