Mapping Amplify Storage.get()



大家好。我正在尝试获得单个S3桶的URL这个工作很完美

const [imageURL, setImageURL] = useState("");
const {
title,
content,
imagePath, //This imagePath is the S3 key
} = article.article;
useEffect(() => {
const getImage = async () => {
try {
const imageAccessURL = await Storage.get(imagePath);
setImageURL(imageAccessURL);//That's how I can get the URL
} catch (error) {
console.error("error accessing the Image from s3", error);
setImageURL("");
}
};
getImage();
}, [imagePath]);

现在我正试图从S3桶映射时获取列表URL。

export default function ArticleComponent() {
const handleImage = async (imagePath) => {
try {
const imageAccessURL = await Storage.get(imagePath);
return imageAccessURL; //I don't know how to apply states or any other methods
} catch (error) {
console.error("error accessing the Image from s3", error);
}
};
const renderList = articles.map((article) => {
const {
id,
content,
title,
imagePath,
} = article;
return (
<Paper className={classes.paper} key={id} elevation={5}>
<img src={handleImage(imagePath)} alt="" /> //I want get URL here 
</Paper>
);
});
return (
<Box>
{renderList}
</Box>
)

,但在最后,在<img src={handleImage(imagePath)} alt="" />它将返回对象promise。文章包括文章列表,imagePath是S3 bucket的键。必须使用这个await Storage.get(key)来获得真正的访问URL,单个可以使用useState,但对于映射,我没有任何想法去做。

希望有人能帮忙!由于

我终于找到了解决办法。使用Promise.all

const {
imageKeys //This imagePath is the S3 key
} = article.article;
const [imgKeyFromServer, setImgKeyFromServer] = useState([]);
useEffect(() => {
const getImage = async () => {
try {
setImgKeyFromServer([]);
const imageAccessURL = await Promise.all(
Array.from(imageKeys).map((key) =>
Storage.get(key, {
level: "public"
})
)
);
setImgKeyFromServer((url) => url.concat(imageAccessURL));
} catch (error) {
console.error("error accessing the Image from s3", error);
setImgKeyFromServer([]);
}
};
console.log("imageKeys", imageKeys);
if (imageKeys) {
getImage();
}
}, [imageKeys]);

这可以从S3存储所有url。

最新更新