for loop fetch api 在状态数组 reactjs 中调用和存储响应

for loop fetch api call and store responses in an state array 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 张图像存储到 targetlist 状态。但是,顺序将全部混乱。我如何确保列表不会因响应 return 的不同时间而混乱?

或者有没有更好的方法可以获取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)
            }))           
        }
      });
 }
}