Javascript 在React中渲染之前获取Firestore数据
我正在尝试创建一个基本配置文件页面,该页面在包含用户的Firestore DB上运行get请求,然后返回找到的用户信息。到目前为止,我的网页从未加载,可能是因为在get请求完成之前调用了render方法。我可以通过console.log语句验证get请求是否正常工作。在从数据库检索到用户后,如何确保页面更新?谢谢Javascript 在React中渲染之前获取Firestore数据,javascript,reactjs,asynchronous,google-cloud-firestore,react-router,Javascript,Reactjs,Asynchronous,Google Cloud Firestore,React Router,我正在尝试创建一个基本配置文件页面,该页面在包含用户的Firestore DB上运行get请求,然后返回找到的用户信息。到目前为止,我的网页从未加载,可能是因为在get请求完成之前调用了render方法。我可以通过console.log语句验证get请求是否正常工作。在从数据库检索到用户后,如何确保页面更新?谢谢 class Profile extends Component{ constructor (props) { super(props); this.state =
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>
);
}
}
类配置文件扩展组件{
建造师(道具){
超级(道具);
此.state={
uid:'样本ID',
用户:null,
isLoaded:false
};
}
组件安装(){
firestore.collection('user').doc(this.state.uid).get()
.然后(res=>{
这是我的国家({
用户:res.data(),
isLoaded:正确
})
}
);
}
render(){
返回(
{this.state.isLoading?欢迎{this.state.user.displayName}:Loading}
);
}
}
它不会加载,因为“this.state.isLoading”未定义,它应该是“this.state.isLoaded”
render(){
返回(
{this.state.isLoaded?欢迎{this.state.user.displayName}:loaded}
);
}
当请求完成时,它将进行设置状态并再次调用渲染,将显示您的数据
render() {
return (
<div>
{this.state.isLoaded? <h3> Welcome {this.state.user.displayName} </h3> : <h3> Loading </h3>}
</div>
);
}