簡體   English   中英

列表中的每個孩子都應該有一個唯一的“關鍵”道具。 (我使用了 Key 仍然出現此錯誤)

[英]Each child in a list should have a unique "key" prop. (I have used the Key still getting this error)

由於我使用了密鑰,但我仍然收到此錯誤。

<>
            <h1>Latest Products</h1>
            {loading ? (
            <h2>loading...</h2>
            ) : error ? (
             <h3>{error}</h3> 
            ) :  
             <Row>
                
                {products.map((product) => (
                    <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
                       
                        <Product product={product} />
                    </Col>
                ))}
            </Row>}

        </>
 

這里有什么問題以及如何解決它。

我認為 product._id 是未定義的,因此對於所有數組元素,值都是相同的。 請控制台 product._id。

正如其他人指出的那樣, product._id可能undefined或不是唯一值(這本身就很糟糕)。 您可以通過將index附加到product._id值來修復錯誤:

<Row>
  {products.map((product, index) => (
    <Col key={`${product._id}-${index}`} sm={12} md={6} lg={4} xl={3}>
      <Product product={product} />
    </Col>
  ))}
</Row>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM