我在firbase中创建了一个存储区,用于存储登录用户的图像,这些图像将作为电子邮件保存在"profile images"文件夹中。
当我试图提取图像时,firebase说它无法读取null的属性电子邮件。
这是我的代码:
import React, { Component } from 'react'
export class AccountPage extends Component {
//the upload of image to firebase cloud storage (works fine)
Upload = (e) => {
let file = e.target.files[0];
let storageRef = firebase
.storage()
.ref("profile-images/" +firebase.auth().currentUser.email);
let task = storageRef.put(file);
}
//storage of the url, no problem stated.
constructor(props) {
super(props)
this.state = {
download: null,
}
}
//always says "cannot read property email of null" even with the if statement
componentDidMount(){
if (firebase.auth().currentUser.email != null)
{
//to define storageRef
let storageRef = firebase
.storage()
.ref("profile-images/" +firebase.auth().currentUser.email);
//location of the highlighted problem,
storageRef.getDownloadURL().then(function(url) {
this.setState({
download:url
});
console.log(url)
})
}
//end of problem's location
}
//the upload file input and the image to be displayed location
render() {
return (
<div>
<img src={this.state.download} height="42" width="42"/>
<input type="file" onChange={this.Upload}/>
</div>
)
}
}
export default AccountPage
欢迎就如何进行提出任何建议,并感谢您花时间研究此问题。
这意味着组件首次装载时firebase.auth().currentUser
为null。
你可以试试
componentDidMount(){
if (firebase.auth().currentUser && firebase.auth().currentUser.email)
// do the other stuff
但如果它没有开火,那么你可能需要用componentDidUpdate
来捕捉它
constructor(props) {
super(props)
this.state = {
download: null,
loginCheck: false,
}
}
componentDidUpdate(prevProps){
if (!prevProps.loginCheck && firebase.auth().currentUser) {
setState({ loginCheck: true });
// do the other stuff
或者,将firebase.auth().currentUser
作为父组件的道具传递,然后使用它。