【发布时间】:2021-05-11 00:35:38
【问题描述】:
我正在开发一个组件,该组件显示一个 pdf 或链接的附件。如果是 pdf,我将显示 pdf_bg 图像,并且该图块将链接到下载页面。如果它是一个链接,我将显示 link_bg,并且该磁贴将链接到该站点。
有一段时间,我的问题集中在将正确的数据放入“url”。如果没有正确使用 async/await,我的 downloadurl 已成功加载,但我的组件仍呈现空标签。最后我设置了你在这里看到的钩子。所以现在网址可以正确加载,但由于某种原因,背景图片没有设置。
更重要的是,我收到关于重新渲染过多的错误。我知道状态挂钩在更新时具有一定的重新渲染行为。我以为我设置的条件可以解决这个问题,但显然不是。
有什么建议吗?
export default function AttachmentTile(props) {
const classes = useStyles();
const attachHandler = attachmentUploader();
let bgimage;
let name = props.attInfo[0];
//for files, the 1st index is the name, 2nd is the ID. for links, 1st is the name but 2nd is the link url
let attID = props.attInfo[1];
let type = props.attInfo[2];
const [url, setUrl] = useState(null);
useEffect(() => {
async function getUrl() {
const downloadUrl = await attachHandler.getDownloadUrl(props.objID, attID);
setUrl(downloadUrl);
}
if(url === null && type === "file")
getUrl();
});
if(props.attachmentImage){
bgimage = props.attachmentImage;
}else if(type === "file"){
bgimage = pdf_bg;
}else if(type === "link"){
bgimage = link_bg;
//in this case, attID isn't actually an ID, it's the url we store for links.
setUrl(attID);
}
if(url === null){
return <h1>Loading...</h1>;
}
return ( AttachmentTile component that uses {url} in an <a> tag )
【问题讨论】:
-
您的
useEffect没有依赖数组,这意味着它在每次组件呈现时都会触发;这可能会导致它,因为它也会更新状态。
标签: reactjs async-await react-hooks jsx