在React中渲染之前获取Firestore数据



我试图创建一个基本配置文件页面,该页面在包含用户的Firestore DB上运行get请求,然后返回找到的用户信息。到目前为止,我的网页从未加载,可能是因为渲染方法在我的get请求完成之前被调用。我可以通过console.log语句验证get请求是否正常工作。我可以做些什么来确保页面更新,一旦用户已经从数据库检索?谢谢!

class Profile extends Component{
constructor (props) {
super(props);
this.state = {
uid: 'sampleID',
user: null,
isLoaded: false
};
}
componentDidMount () {
firestore.collection('user').doc(this.state.uid).get()
.then(res => { 
this.setState({
user: res.data(),
isLoaded: true
})
}
);
}
render() {
return (
<div>
{this.state.isLoading ? <h3> Welcome {this.state.user.displayName} </h3> : <h3> Loading </h3>}
</div>
);
} 
}

无法加载,因为"this.state.isLoading"未定义,则应该是"this.state.isLoaded">

render() {
return (
<div>
{this.state.isLoaded? <h3> Welcome {this.state.user.displayName} </h3> : <h3> Loading </h3>}
</div>
);
} 

当请求完成时,它将使setState并再次调用渲染,您的数据将被显示。

最新更新