简体   繁体   English

在映射函数中反应条件语句

[英]React conditional statement within a map function

I am displaying reviews from the Google Maps API.我正在显示来自 Google Maps API 的评论。 Within my map function I only want to display reviews that are higher than a 1 rating.在我的地图功能中,我只想显示评分高于1评论。 How can I update my map function to only display reviews where review.rating > 1 ?如何更新我的地图功能以仅显示review.rating > 1评论?

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

Just filter them before map:只需在映射之前过滤它们:

{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>
    ))
}

If, for some reason you don't want to call the .filter method on the array, you could do something like this.如果由于某种原因您不想在数组上调用.filter方法,您可以执行以下操作。 Basically you are calling a ternary operator in your return.基本上,您在返回时调用了三元运算符。 Let me know if you need any more explanation.如果您需要更多解释,请告诉我。

 {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