我正在做一个带有react的小型应用程序,将图片放在私有S3存储桶中,只有注册用户可以访问它。我根本没有网页设计方面的经验(我是一名数据科学家),所以也许我遵循的策略并不是最有效的策略。 但是,我通过Cognito进行了注册和登录,并且可以正常工作。在身份池上,我将读取角色置于存储桶中。现在,我正在尝试在该存储桶中渲染示例图片。
这是我现在拥有的代码:
import React, { useState } from "react";
import { Storage } from "aws-amplify";
export default function LoadImage(props){
const [imgUrl, setImgUrl] = useState("");
async function onLoad(){
try{
const url = await Storage.get(props);
setImgUrl(url);
}
catch(e){
alert(e);
}
}
onLoad();
return(
<img src={imgUrl} />
);
}
,并打算在App.js
中使用它,
<div>{isAuthenticated ? LoadImage("img/images.png") : <>"No pic 4 u"</>}</div>
这段代码给我错误Rendered more hooks than during the previous render.
。忍受我,我不知道这是什么钩子,因为我正在从互联网上挑选代码示例。我尝试将其直接放置在<img>
标记中
<div>{isAuthenticated ? <img src={Storage.get("img/images.png")} /> : <>"No pic 4 u"</>}</div>
但是当我检查html时,它显示为
<div>{isAuthenticated ? <img src=[Object Promise] /> : <>"No pic 4 u"</>}</div>
同样,我对promise知之甚少(来自react文档)。如果我输入了alert(Storage.get("img/images.png"))
,则会显示正确的网址。
答案 0 :(得分:1)
我认为您绝对应该先阅读一些文档并熟悉基础知识。 无论如何,这是您应该如何做:
export default function LoadImage({link}){
const [imgUrl, setImgUrl] = useState("");
async function onLoad(){
try{
const url = await Storage.get(link);
setImgUrl(url);
}
catch(e){
alert(e);
}
}
useEffect(onLoad, []);
return(
<img src={imgUrl} />
);
}
并这样称呼它:
<div>{isAuthenticated ? <LoadImage link="img/images.png"/> : <>"No pic 4 u"</>}</div>
答案 1 :(得分:0)
它可能看起来像这样:
2019-11-24 16:24:57.606 26016-26016/com.example.photo_sharing D/GROUP OWNER ADDRESS: 192.168.49.1
2019-11-24 16:24:57.607 26016-26016/com.example.photo_sharing D/IP ADDRESS: 192.168.0.2
2019-11-24 16:24:57.608 26016-26016/com.example.photo_sharing D/Method: ******In pre Execute
2019-11-24 16:24:57.609 26016-26016/com.example.photo_sharing D/Receive Activity: Opening client socket
2019-11-24 16:24:57.610 26016-26053/com.example.photo_sharing D/GROUP OWNER ADDRESS: #########192.168.49.1
2019-11-24 16:24:57.610 26016-26053/com.example.photo_sharing D/Receive Activity: Opening client socket -
2019-11-24 16:24:57.614 26016-26053/com.example.photo_sharing E/Receive Activity: failed to connect to /192.168.49.1 (port 9990) from /192.168.49.1 (port 44461) after 500000ms: isConnected failed: ECONNREFUSED (Connection refused)
对于每个组件,不应多次使用此挂钩。如果确实需要多个图像,则可以将其包装在组件中:
export default function useLoadImage(url, isAuthenticated) {
const [imgUrl, setImgUrl] = useState(
isAuthenticated ? '' : <>"No pic 4 u"</>
);
useEffect(() => {
async function onLoad() {
try {
const iUrl = await Storage.get(url);
//should check if component is still mounted before trying to set state
//https://github.com/jmlweb/isMounted
setImgUrl(iUrl);
} catch (e) {
alert(e);
}
}
isAuthenticated && onLoad(); //only call if is authenticated
}, [url, isAuthenticated]); //only do again if url or is authenticated changes
return <img src={imgUrl} />;
}
//using the custom hook
const img = useLoadImage('url', isAuthenticated);