【问题标题】:React Image src undefined - AWS S3反应图像 src 未定义 - AWS S3
【发布时间】:2022-01-17 07:42:58
【问题描述】:

我有一个:

<img src={ "http://127.0.0.1:5001/api/users/profile_photo/" + user.profile_photo }
     className="img-fluid rounded-circle"
     alt="rounded image"/>

每当我在页面中加载时,函数getUser() 就会运行并检索用户。

const getUser = async () => {
  let user = await axiosWithAuth().get('/users/' + userId);
  setUser(user.data);
};

user.profile_photo 是我从 AWS s3 取回的密钥。前任。 43256722324654

问题: 当页面加载时,图像 src 尚未设置为它的样子,因为在 express 后端,profile_photo 来自未定义。它在第二次循环时被定义。

因此,AWS 会为 noSuchKey 抛出错误

/Users/timbogdanov/Desktop/hlam/server/node_modules/AWS-SDK/lib/request.js:31 抛出错误; ^

NoSuchKey:指定的键不存在。

在设置用户状态对象之前,有什么方法可以阻止图像发送获取请求?

谢谢!

【问题讨论】:

    标签: javascript node.js reactjs amazon-web-services amazon-s3


    【解决方案1】:

    添加渲染图像的条件。如果user.profile_photo 未定义,则不要渲染它。

    {user.profile_photo && <img src={ "http://127.0.0.1:5001/api/users/profile_photo/" + user.profile_photo }
         className="img-fluid rounded-circle"
         alt="rounded image"/>
    }
    

    【讨论】:

    • 非常感谢,我不知道我是怎么错过的。感谢您的编辑!
    猜你喜欢
    • 2021-11-13
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2017-12-20
    • 2013-04-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多