如何在ReactJS中返回数组的第一个对象

时间:2020-10-02 12:36:07

标签: reactjs react-hooks

我试图返回数组的第一个对象,我该如何实现。

{ products && products.map((product,i)=>(
       <div key={i} >
          <h6>{product.name} - {product.category.name}</h6>
          <p className="mb-0"> {product.price} returns in {product.duration} months</p>
       </div>
   ))
 }

1 个答案:

答案 0 :(得分:0)

如果您对映射整个数组不感兴趣,只需获取第一项,您可以改用index:

( *)  # match a sequence starting with 0 or more spaces
XX    # followed by XX
(,*)  # followed by 0 or more commas
( *)  # followed by 0 or more spaces

注意:顺便说一下,{ products && products[0] && ( <div> <h6>{products[0].name} - {products[0].category.name}</h6> <p className="mb-0"> {products[0].price} returns in {products[0].duration} months</p> </div>) )) } 在JS中被视为真实值,因此您应该使用[]而不是!!products.length