[英]Image is fetched from firebase storage but src value is unable to set in react ANTD Avatar component
I am using Avatar antd component.我正在使用 Avatar antd 组件。 My image is fetched from the Firebase storage.我的图像是从 Firebase 存储中获取的。
Here is the code which I already implemented.这是我已经实现的代码。
test = (imageName) => {
if (imageName)
{
firebaseConfig.storage().ref().child(`users/${imageName}`).getDownloadURL().then(url => {
return url;
})
}
else{
return "https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png";
}
}
Here imagename will be considered as child name as you can see in the code.正如您在代码中看到的那样,此处的 imagename 将被视为子名称。
Now, I will show you How I call that function from the class component.现在,我将向您展示如何从 class 组件中调用 function。
<Avatar src={this.test(imagename)} />
It is working fine if imagename is null.如果 imagename 是 null,它工作正常。
Would you please help me to do so as I am new for React and Firebase.你能帮我这样做吗,因为我是 React 和 Firebase 的新手。
The problem is that when imageName
is not null, you use a promise to fetch the url from firebase.问题是当imageName
不是 null 时,您使用 promise 从 ZBF12E15215C213ABB9DA8 获取 url This means that an asynchronous operation will start (calling firebase for the url), and when it finishes the function you passed to the then
will be called with the url that was found.这意味着将开始一个异步操作(为 url 调用 firebase),当它完成 function 时,您传递给then
将使用找到的 Z572D4E421E5E6B9BC11D815E8A027 调用。
The problem is that returning from inside the promise doesn't return it from the function (since the function already returns while the asynchronous operation goes on in the background.问题是从 promise 内部返回不会从 function 返回它(因为 function 已经返回,而异步操作在后台进行。
The solution in react for this problem would be to use state to store the url, and update it from within the then
when the promise resolves.解决此问题的解决方案是使用 state 存储 url, then
在 promise 解决时从内部更新它。
In that case you will call the test
function on the component mount, and instead of returning the url, it will set it to the state
.在这种情况下,您将在组件安装上调用test
function,而不是返回 url,而是将其设置为state
。
test = (imageName) => {
if (imageName)
{
firebaseConfig.storage().ref().child(`users/${imageName}`).getDownloadURL().then(url => {
this.setState({imageUrl: url});
})
}
else{
this.setState({imageUrl: "https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"});
}
}
Then you can use it from the state
like this:然后你可以像这样从state
使用它:
<Avatar src={this.state.imageUrl} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.