簡體   English   中英

在映射函數中反應條件語句

[英]React conditional statement within a map function

我正在顯示來自 Google Maps API 的評論。 在我的地圖功能中,我只想顯示評分高於1評論。 如何更新我的地圖功能以僅顯示review.rating > 1評論?

{this.state.reviews && this.state.reviews.map((review, index) => (
    <div key={index} className="review">
        <p>{review.text}</p>
    </div>
))}

只需在映射之前過濾它們:

{this.state.reviews
    .filter((review) => review.rating > 1) // get only reviews with rating > 1
    .map((review, index) => (
       <div key={index} className="review">
          <p>{review.text}</p>
       </div>
    ))
}

如果由於某種原因您不想在數組上調用.filter方法,您可以執行以下操作。 基本上,您在返回時調用了三元運算符。 如果您需要更多解釋,請告訴我。

 {this.state.reviews && this.state.reviews.map((review, index) => ( review.index > 1 ? (<div key={index} className="review"> <p>{review.text}</p> </div>) : null ))}

暫無
暫無

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

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