[英]Variable is used before being assigned (TypeScript)
I am trying to get the ImgString inside of an array that I get back from an API and assign that string it to the base64 property of the photo object but it display this the error.我正在尝试获取从 API 返回的数组中的 ImgString,并将该字符串分配给照片 object 的 base64 属性,但它显示此错误。 I am new to react and tyescript/javascript so I am not sure where did it go wrong.
我是新来的反应和 tyescript/javascript,所以我不确定 go 哪里出错了。
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;
}
Your photo
variable is declared but not assigned when you write (Hence the error - "used" before "assigned"):您的
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
You should either write this:你应该这样写:
var photo: Photo = {}; // declaration + assignment
photo.base64 = `data:image/jpeg;base64,${res.data[i].ImgString}`;
photos.push(photo);
or或者
var photo: Photo = {
base64: `data:image/jpeg;base64,${res.data[i].ImgString}`,
} // declaration + assignment
photos.push(photo)
You can read the difference between declaration and definition .您可以阅读声明和定义之间的区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.