简体   繁体   English

React JSX:条件数组中的唯一键提示

[英]React JSX: Unique Key Prop in Conditional Array

In a child-less React component, I'm getting the "unique key prop" error due to my use of an array inside a JSX conditional: 在一个没有子项的React组件中,由于我在JSX条件中使用了一个数组,我得到了“unique key prop”错误:

Each child in an array should have a unique "key" prop. 数组中的每个子节点都应该具有唯一的“键”支柱。

The code that's triggering the error looks like this: 触发错误的代码如下所示:

<dl>
  { item.sale ? 
    [<dt>Sale</dt>,<dd className="formatted">{item.sale}</dd>,<dt>SRP</dt>,<dd>{item.srp}</dd>] :
    [<dt>Price</dt>,<dd className="formatted">{item.srp}</dd>]
  }
</dl>

I understand why the key prop is needed when rendering child components, but how do I satisfy React/JSX when the "child in an array" is an arbitrary set of child elements like this? 我理解为什么在渲染子组件时需要关键道具 ,但是当“数组中的子”是像这样的任意子元素集时,如何满足React / JSX?

React can't know that your array is static, so you get the warning. React无法知道您的数组是静态的,因此您会收到警告。 The most practical thing to do here is to write something like: 这里最实际的做法是写下这样的东西:

var dl;
if (item.sale) {
  dl = <dl key="sold">
    <dt>Sale</dt>
    <dd className="formatted">{item.sale}</dd>
    <dt>SRP</dt>
    <dd>{item.srp}</dd>
  </dl>;
} else {
  dl = <dl key="unsold">
    <dt>Price</dt>
    <dd className="formatted">{item.srp}</dd>
  </dl>;
}

Providing the keys on the root tells React how it should reconcile the lists when item.sale changes. 在根上提供密钥告诉React当item.sale更改时它应如何协调列表。

I tend to find this easier to read as well. 我倾向于发现这也更容易阅读。

I also had a similar issue and I solved the problem adding key={index} in the following code. 我也有类似的问题,我解决了在以下代码中添加key={index}的问题。

this.state.shopList.map((shop, index) => {
          return (
            <Table.Row key={index}>
              <Table.Cell collapsing>{shop.shopName}</Table.Cell>
              <Table.Cell collapsing>{shop.email}</Table.Cell>
              <Table.Cell collapsing>{shop.shopAddress}</Table.Cell>
              <Table.Cell collapsing>{shop.approved}</Table.Cell>
              <Table.Cell collapsing>{shop.iban}</Table.Cell>
            </Table.Row>
          );
        })}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM