0
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字符串。图像存储在本地内存中。

4

2 回答 2

0
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)
            }))           
        }
      });
 }
}
于 2020-06-06T17:39:30.760 回答
0

你可以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)
        }))
   }
 }
}
于 2020-06-06T17:21:12.527 回答