我有一个div,我想用数组元素填充,可以是图像或视频。为此,我使用Fetch API来解析每个元素的标头,并获取内容类型,然后我想使用该内容类型来呈现图像或视频。
这是问题所在。我有2个辅助函数,一个用于视频的图像。这是我想要这样做的方式,但是(假设是因为异步调用),辅助函数被调用而没有渲染。我知道渲染助手肯定是有效的。
checkFileType(url){
fetch(url, {
method: "HEAD",
headers: {
"Content-Type": "application"
}
}).then((res) => {
var content = res.headers.get("content-type");
if (content === "image/jpeg"){
this.renderSIVImage(this.props.item.detail_image_urls[this.state.index]);
}
console.log(content);
}, function(e) {
alert("Error!");
});
}
所以我尝试使用状态变量来跟踪,因为局部变量在获取后被废弃。像这样的东西。然后我检查HTML中的文件类型。这是有效的,但console.logs告诉我它不断重新渲染,这显然是低效的。
checkFileType(url){
fetch(url, {
method: "HEAD",
headers: {
"Content-Type": "application"
}
}).then((res) => {
var content = res.headers.get("content-type");
if (content === "image/jpeg"){
this.setState({
filetype: "image"
})
}
console.log(content);
}, function(e) {
alert("Error!");
});
}
必须有一个很好的解决方案,有没有人有想法?我顺便使用React和Django。
编辑:这是我称之为的地方。 CheckFileType函数本质上只是一个fetch帮助器。我传递的URL是我本地数据库的链接,但在生产时它将是我的s3存储桶的链接。
<Swipeable
onSwipedLeft={()=>this.cycleImages("forward")}
onSwipedRight={()=>this.cycleImages("backward")}
style={{height:"50%"}}>
<div>
{this.checkFileType(this.props.item.detail_image_urls[this.state.index])}
</div>
</Swipeable>
首先,如果有人能告诉我为什么它会多次更新状态,即使我似乎只打了一次,我仍然很好奇。
不过,我想出了解决方案的解决方法。这些图像/视频是在一个旋转的旋转木马,所以我HEAD fetch
曾在componentDidMount
为初始图像,然后我在逻辑中添加另一个HEAD fetch
移动旋转木马。这样,每个轮播运动仅与一个标题检查相关联。