![](/img/trans.png)
[英]i fetched an api data and put in and object of a state , and iwant to sort that fetched array , and display it
[英]Problem with fetched data put into and object
我從 api 中獲取了一個隨機圖像(它是對象),我想把它放到 object 中的一個對象中來處理這個圖像。 當我在控制台記錄“數據”時一切正常,我可以看到這個圖像對象,但是當我在控制台記錄“data.image”時,控制台返回一個空對象,它應該是獲取的對象。 我是初學者。
let data = {
image: {},
votes: []
}
async function getImage() {
let img = await fetch(data.getImgUrl, {
method: "GET",
})
const newImg = await img.json();
data.image = await newImg[0]
}
當我在控制台記錄“數據”時
控制台記錄我:圖像{這里是包含此獲取數據的屬性}和投票:[]
當我在控制台記錄“data.image”時
控制台記錄我:圖像{作為一個空對象}
您獲取了一個圖像,但您嘗試將其解碼為 JSON。 這是行不通的。 您需要執行以下操作(我沒有寫過),我從這里獲得它使用 arrayBuffer。
// we use this to get the immage from the buffer
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = [].slice.call(new Uint8Array(buffer));
bytes.forEach((b) => binary += String.fromCharCode(b));
return window.btoa(binary);
};
fetch(request, options).then((response) => {
response.arrayBuffer().then((buffer) => {
// make an image from the buffer
var imageStr = arrayBufferToBase64(buffer);
// use image where you want. e.g. out it into an image tag
document.querySelector('img').src = 'data:image/jpeg;base64,'+ imageStr;
});
});
這也可能值得一讀: https : //developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.