gpt4 book ai didi

javascript - 变量在分配之前使用(TypeScript)

转载 作者:行者123 更新时间:2023-12-02 20:48:48 25 4
gpt4 key购买 nike

我试图获取从 API 返回的数组内的 ImgString 并将该字符串分配给照片对象的 base64 属性,但它显示了错误。我是 React 和 tyescript/javascript 新手,所以我不确定哪里出了问题。

import { useState, useEffect } from "react";



export function getImages () {
const [photos, setPhotos] = useState<Photo[]>([]);


const GetPhotoURL = "***"


useEffect(() => {
const loadSaved = async () => {
const data = await axios.get(GetPhotoURL)
.then(res => {

const photos = [] as Photo[];

for (let i = 0; i <= res.data.length; i++) {
var photo: Photo;

photo.base64 = `data:image/jpeg;base64,${res.data[i].ImgString}`;

photos.push(photo);
}

setPhotos(photos);
})

};
loadSaved();
}, []);
return {
photos,
};
}
export interface Photo {
base64?: string;
}

最佳答案

您的 photo 变量在您写入时已声明但未分配(因此出现错误 - 在“分配”之前“使用”):

var photo: Photo; // line 1
photo.base64 = `data:image/jpeg;base64,${res.data[i].ImgString}`; // line 2
// at line 2, you are trying to access the base64 property of photo which is not yet assigned

你应该这样写:

var photo: Photo = {}; // declaration + assignment
photo.base64 = `data:image/jpeg;base64,${res.data[i].ImgString}`;
photos.push(photo);

var photo: Photo = {
base64: `data:image/jpeg;base64,${res.data[i].ImgString}`,
} // declaration + assignment
photos.push(photo)

您可以阅读difference between declaration and definition .

关于javascript - 变量在分配之前使用(TypeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61668661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com