我正在尝试从 Firebase 存储中检索图像 url,然后使用该 url 设置图像。但是,似乎我正在使用当前代码将 src 设置为未定义的值:
这是我用来从 Firebase 存储中检索的函数
import {Firebase,
FirebaseAuth,
FirebaseDatabase,
FirebaseStorage} from '../Initialize'
export function getProfilePictureUrl(uid, callback, onErrorCallback) {
var pathReference = FirebaseStorage.ref('profiles/' + uid + '/profilePicture.jpeg');
pathReference.getDownloadURL().then((url) => {
callback(url);
}).catch((error) => {
onErrorCallback(error);
});
}
我从使用如下函数的 React 组件调用它:
render() {
let profilePictureUrl = getProfilePictureUrl(uid, (url) => {
console.log(url); // The console.log(url) returns a valid and working url for the image. So I know my imports are correct
return url;
},
(error) => {
console.log(error.code);
return "";
})
return (
<img
src={profilePictureUrl}
/>
);
}
图片未正确加载,因为 ProfilePictureUrl 返回未定义。
我也曾尝试在 render() 中创建一个测试器,如下所示:
render() {
if(profilePictureUrl !== undefined) {
console.log("defined");
}
else {
console.log("undefined");
}
// returns 'undefined'
}
我正在记录 else 响应,表明该函数正在返回一个未定义的值。我怀疑它与 Firebase 的异步特性有关,但我不确定如何解决它。
这个问题可能与:React-Native: Download Image from Firebase Storage有关
最佳答案
通过谷歌找到这个并决定回答以防其他人也找到它。
您的示例不起作用,因为 React 不会在 promise 解析时更新组件。这意味着您的图像 URL 保持未定义
。
要解决此问题,您可以在 promise 中调用 this.setState()
(如果您使用的是 flux/redux,则可以分派(dispatch)一个操作)。这将使用新 URL 自动为您更新状态。
代码示例
const config = {
apiKey: "apiKey",
authDomain: "authDomain",
storageBucket: "bucketURL"
}
firebase.initializeApp(config)
const storage = firebase.storage().ref()
class HelloMessage extends React.Component {
constructor () {
super()
this.state = {
lithuania: '',
uk: ''
}
this.getImage('lithuania')
this.getImage('uk')
}
getImage (image) {
storage.child(`${image}.png`).getDownloadURL().then((url) => {
this.state[image] = url
this.setState(this.state)
})
}
render() {
return (
<div>
Hello Lithuania<br />
<img src={ this.state.lithuania } alt="Lithuanian flag" />
<br />
Hello United Kingdom<br />
<img src={ this.state.uk } alt="UK flag" />
</div>
);
}
}
关于javascript - 从 Firebase 存储加载图片到 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421475/