【问题标题】:React Component requires a unique key propReact 组件需要一个唯一的 key prop
【发布时间】:2019-06-23 11:34:05
【问题描述】:

我制作了一个创建组件,它可以渲染所有看起来不错的东西,但是当我在浏览器中执行控制台时,它出现以下错误。

index.js:2178 警告:数组或迭代器中的每个子元素都应该有 一个独特的“关键”道具。

我尝试了关键道具,但仍然出现此错误。请在下面查看我的代码并提出建议!非常感谢。

    const serviceList = (props) => (

  <CardBody style={{ backgroundImage: `url(${ServiceBgImg})` }}>

    <div>
      <h3 style={{ fontWeight: 'bold' }}
      >{props.groupName}</h3>
      {props.allServices.filter(groupedServices => groupedServices.category === props.groupName)
        .map(serviceInfo =>
          <List component='nav'>
            <ListItem>
              <ListItemText primary={
                <div key={serviceInfo.id}>
                  <h5  style={{ fontWeight: 'bold' }}>
                    <span>{serviceInfo.service}</span>
                    <span
                      style={{ float: 'right' }}
                    >{serviceInfo.price}</span>
                  </h5>
                  <h5>
                    {serviceInfo.description}
                  </h5>
                </div>
              }
              />
            </ListItem>
          </List>
        )
      }
    </div>

  </CardBody>
);

export default serviceList;

【问题讨论】:

  • 您的List 应该得到密钥,而不是List 中的div

标签: reactjs key unique react-props


【解决方案1】:

您的 List 组件应该包装 map 函数,并在其中添加映射 ListItems 的键:

<List component='nav'>
...
.map((serviceInfo, index) =>
    <ListItem key={index}>
      ...
    </ListItem>
    ....

【讨论】:

    【解决方案2】:

    map 函数返回的最外层/父元素需要有一个key 属性。在您的情况下,它不是&lt;div&gt;,而是&lt;List&gt;,这似乎是一个错误,因为您似乎想遍历allServices 的过滤结果以创建serviceInfo 的列表。如果是这种情况,您应该将 map 函数移动到 &lt;ListItem&gt; 的正上方,并将 key 属性分配给它。

    代码示例如下:

    const serviceList = (props) => (
      <div>
        <h3 style={{ fontWeight: 'bold' }}>{props.groupName}</h3>
      <List component='nav'>
      {props.allServices.filter(groupedServices => groupedServices.category === props.groupName).map(serviceInfo =>
        <ListItem key={serviceInfo.id}>
          <ListItemText primary={
             <div key={serviceInfo.id}>
               <h5 style={{ fontWeight: 'bold' }}>
                 <span>{serviceInfo.service}</span>
                 <span
                   style={{ float: 'right' }}
                 >{serviceInfo.price}</span>
               </h5>
               <h5>{serviceInfo.description}</h5>
            </div>
           }/>
       </ListItem>)}
     </List>
    
    </div>);
    export default serviceList;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-15
      • 2022-08-08
      • 2018-12-22
      • 2017-04-30
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 2018-04-26
      相关资源
      最近更新 更多