簡體   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