如何从包含某些内容的地图中获取第一个元素?
How to get First element from a map that includes something?
我正在尝试 select api 中包含图像的第一个路径目录,以便我可以将值设置为图像源并显示第一个图像,但是当我使用 fl[ 0] 我得到所有值
这是代码:
{useLesson &&
useLesson.files.map((fl, index) => {
if (fl.mimetype.includes("image")) {
// this always get all values not only the first value
console.log(fl[0])
// and this always gives me infinite loop issue
setSelectedImage(fl[0])
return (
<div key={index}>
<img src={axiosUse + fl.path} alt="" />
</div>
)
}
})
}
我怎样才能只从包含某些内容的地图中获取第一个值?
我想做的是从服务器获取文件,如果它是一个图像文件,则显示一些组件,但我怎样才能只获取第一个图像值文件?
您可以创建一个新组件来显示第一个文件
const FilePreview = ({ mimetype, files, basepath }) => {
const firstFileOfType = files.find((file) =>
file.mimetype.includes(mimetype)
);
if (!firstFileOfType) return null;
return (
<div>
<img src={basepath + firstFileOfType.path} alt="" />
</div>
);
};
并将其用作
{useLesson && (
<FilePreview
mimetype="image"
files={useLesson.files}
basepath={axiosUse}
/>
)}
我正在尝试 select api 中包含图像的第一个路径目录,以便我可以将值设置为图像源并显示第一个图像,但是当我使用 fl[ 0] 我得到所有值
这是代码:
{useLesson &&
useLesson.files.map((fl, index) => {
if (fl.mimetype.includes("image")) {
// this always get all values not only the first value
console.log(fl[0])
// and this always gives me infinite loop issue
setSelectedImage(fl[0])
return (
<div key={index}>
<img src={axiosUse + fl.path} alt="" />
</div>
)
}
})
}
我怎样才能只从包含某些内容的地图中获取第一个值?
我想做的是从服务器获取文件,如果它是一个图像文件,则显示一些组件,但我怎样才能只获取第一个图像值文件?
您可以创建一个新组件来显示第一个文件
const FilePreview = ({ mimetype, files, basepath }) => {
const firstFileOfType = files.find((file) =>
file.mimetype.includes(mimetype)
);
if (!firstFileOfType) return null;
return (
<div>
<img src={basepath + firstFileOfType.path} alt="" />
</div>
);
};
并将其用作
{useLesson && (
<FilePreview
mimetype="image"
files={useLesson.files}
basepath={axiosUse}
/>
)}