[英]I have a array of objects containing images and documents, I want to check the mime_type and pick the first element (React) to display in <img> tag
I have a array of objects which contain images and documents, I want to check is the mime_type is 'images/jpeg' or 'image/png' and then only display the first image in a tag.我有一个包含图像和文档的对象数组,我想检查 mime_type 是“images/jpeg”还是“image/png”,然后只显示标签中的第一个图像。 I am using react.我正在使用反应。
I tried this but I keep getting undefined我试过了,但我一直不确定
<img className={"img-fluid img-list"}
src={this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png') || {})[0].blob_url}
alt="" />
<img className={"img-fluid img-list"}
src={this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png'))[0].blob_url}
alt="" />
if check with a {} i dont get any links如果用 {} 检查我没有得到任何链接
any help much appriciated.任何帮助都非常感谢。
You have an error here:你在这里有一个错误:
this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png') || {})[0].blob_url
It should be:它应该是:
((this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png')) || [])[0] || {}).blob_url
If you add a bit of indentation, it should be more clear where your error was:如果您添加一些缩进,应该更清楚您的错误在哪里:
(
(
this.state.images.filter(img => (
img.mime_type === 'image/jpeg' || img.mime_type === 'image/png'
)) // give me an array with only the images
|| [] // OR give me back an empty array if you cannot find any
)[0] // then give me the first element (image object) of the array
|| {} // OR give me back an empty object if the array is empty
).blob_url // finally give me the `blobl_url` of the object
Alternatively, you can use Array.prototype.find
, which will return the first item matching the criteria:或者,您可以使用Array.prototype.find
,它将返回符合条件的第一个项目:
(this.state.images.find(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png')) || {}).blob_url
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.