【发布时间】:2021-01-09 21:24:45
【问题描述】:
如何访问以 Promise[] 形式存储在 ES6 数组中的数据?我正在从后端加载一个数组,每个对象都有一个图像的 url。因此,为了渲染图像,我必须异步/等待获取每个对象的图像。我没有返回 Base64 图像,而是将图像嵌入到 Promise 中。我需要一种读取图像数据的方法。返回对象结构见下图。
请注意,我在后台使用 axios 而不是 Fetch API
以下是分两步加载列表和图片的函数和服务方法。
1.1 axios服务方式
listAllItems() {
return axios.get(API_URL + "docman/items/list/all");
}
1.2 ReactJS 主函数
async componentDidMount() {
try {
const items = await DocmanService.listAllItems();
const itemsData = items.data;
const data = await itemsData.map(item => {
const image = this.loadImage(item.image);
return { ...item, image: image }
})
this.setState({ items: data });
} catch (e) {
console.log(e);
}
}
2.1 Axios图片服务方法
loadImage = (url) => {
return axios.get(API_URL + url, { responseType: 'arraybuffer' });
}
2.2 ReactJS 图片加载器功能
async loadImage(imageUrl) {
try {
return await ImageService.loadImage(imageUrl)
} catch (e) {
return '';
}
}
3.1 从后端获取的 Json 列表
[
{
"id": "1",
"uuid": "1c0a33af-4e78-4823-b84e-f3b5464db2af",
"identifier": "EN ISO 8402",
"title": "EN ISO 8402 Quality Management - Vocabulary",
"folder": "e347fef9-0a76-4e62-b7f2-c78e9f88355b",
"media": "FILE",
"path": "document/id/105",
"image": "image/id/106",
"format": "PDF",
"authors": "",
"publishers": "",
"created": "2020-09-22T14:56:31.316+00:00",
"published": null,
"version": "1994",
"status": null
},
{
"id": "2",
"uuid": "16a0e658-b444-4b60-bf18-ba2786d5fb00",
"identifier": "ISO 14001",
"title": "ISO 14001 Environmenatl Management Systems - Requirements with Guidance for Use",
"folder": "e347fef9-0a76-4e62-b7f2-c78e9f88355b",
"media": "FILE",
"path": "document/id/107",
"image": "image/id/108",
"format": "PDF",
"authors": "",
"publishers": "",
"created": "2020-09-22T14:56:31.659+00:00",
"published": null,
"version": "2004",
"status": null
},
-
-
]
【问题讨论】:
标签: reactjs promise async-await axios base64