对于循环获取 API 调用并将响应存储在状态数组 ReactJS 中


getTarget(filepath){
const filepaths = [target1, target2, target3, target4]
for (var i =0; i< filepaths.length; i++){
var filepath = filepaths[i]
fetch(filepath)
.then((response) => response.blob())
.then(data => { 
var reader = new FileReader();
reader.readAsDataURL(data); 
reader.onloadend = (event)=> {
var base64data = reader.result;
this.setState(prevState => ({
targetlist: prevState.targetlist.concat(base64data)
}))           
}
});
}

目标 1-4 是我必须转换为 base64 并以有序数组存储在 Web 应用程序中的图像。我能够将 4 张图像存储到目标列表状态。但是,订单将全部混乱。如何确保列表不会因响应返回的不同时间而混乱?

或者有没有更好的方法,我能够获得 base64 字符串。图像存储在本地内存中。

你可以像这样使用async/await

async function getTarget(filepath) {
const filepaths = [target1, target2, target3, target4]
for (let i =0; i< filepaths.length; i+=1){
const filepath = filepaths[i]
const data = await (await fetch(filepath)).blob();
const reader = new FileReader();
reader.readAsDataURL(data); 
reader.onloadend = (event) => {
const base64data = reader.result;
this.setState(prevState => ({
targetlist: prevState.targetlist.concat(base64data)
}))
}
}
}
getTarget(filepath){
const filepaths = [target1, target2, target3, target4]
for (var i =0; i< filepaths.length; i++){
var filepath = filepaths[i]
fetch(filepath)
.then((response) => [i, response.blob()])
.then(data => { 
var reader = new FileReader();
reader.readAsDataURL(data[1]); 
reader.onloadend = (event)=> {
var base64data = reader.result;
this.setState(prevState => ({
...prevState,
// just replace that index's value - so that list will be ordered.
targetlist: prevState.targetlist.map((item, index) => (index===i) ? base64data : item)
}))           
}
});
}
}

相关内容

  • 没有找到相关文章

最新更新