繁体   English   中英

从 Promise(ReactJS 和 Axios)中提取图像数据

[英]Extracting images data from Promise (ReactJS and Axios)

如何访问以 Promise[] 形式存储在 ES6 数组中的数据? 我正在从后端加载一个数组,每个对象都有一个图像的 url。 所以为了渲染图像,我必须异步/等待为每个对象获取图像。 我得到的不是返回 Base64 图像,而是将图像嵌入到承诺的深处。 我需要一种方法来读取图像数据。 有关返回对象结构,请参见下图。

请注意,我在后台使用axios不是Fetch API

Image 字段包含一个 promise 而不是 Base64 数据

下面是分两步加载列表和图片的函数和服务方法。

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
  },
  -
  -
]

尝试做image.then((data) => { // console.log(data) })

当您 setState 时,您正在使用具有作为承诺的图像值的对象列表设置新状态。 难道您不应该仅在至少一个承诺解析为真实图像时才更新状态吗? 你不能做类似 this.loadImage(item.image).then((imageData=>setState(适当的 State))) 的事情吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM