首页 > 解决方案 > “警告:列表中的每个孩子都应该有一个唯一的“key”道具“用于包含数组中“key”属性的对象

问题描述

该组件MyComp接受一组对象,它将从中构造按钮。我还key为每个对象提供了一个。在这种情况下,应从 1 元素对象数组创建 1 个 Button:

<MyComp 
    buttons={[{"key":"approvalsButton","variant":"info","text":"Approvals Queue","url":"/approvals"}]} />

组件定义

export default function MyComp(props) {
    return (

        <Col lg={6} className="home-tile">
            <div className="home-tile-content">
                <div className="home-tile-buttons">                 
                    {
                        /* Loop through specified Buttons (if any) and their object attributes */
                    
                        props.buttons 
                        ?                   
                            props.buttons.map(button => (
                                <LinkContainer to={button.url}>
                                    <Button key={button.key} variant={button.variant}>{button.text}</Button>
                                </LinkContainer>
                            ))
                        :
                            ''  
                    }
                </div>
            </div>
        </Col>

但我仍然得到

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

Check the render method of `MyComp`. See https://reactjs.org/link/warning-keys for more information.

标签: reactjs

解决方案


正如错误所述,正在渲染的元素map需要一个key属性来唯一标识它们。这与您正在使用的对象它们是否具有名为的属性无关key,这只是指正在渲染的实际组件。在这种情况下<LinkContainer>

在大多数情况下,您不需要使用此属性,但框架会使用。因此,在大多数情况下,您可以简单地使用map回调的第二个参数,即集合的索引。例如:

props.buttons.map((button, i) => (
  <LinkContainer key={i} to={button.url}>
    <Button variant={button.variant}>{button.text}</Button>
  </LinkContainer>
))

如果您的数组中的对象确实具有独特的属性,那么您也可以轻松地使用它:

props.buttons.map(button => (
  <LinkContainer key={button.key} to={button.url}>
    <Button variant={button.variant}>{button.text}</Button>
  </LinkContainer>
))

推荐阅读