javascript - 在 React 中渲染之前获取 Firestore 数据
问题描述
我正在尝试创建一个基本配置文件页面,该页面在包含用户的 Firestore 数据库上运行获取请求,然后返回找到的用户信息。截至目前,我的网页从未加载,可能是因为在我的 get 请求完成之前调用了 render 方法。我可以通过 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 并再次调用渲染,您的数据将被显示。
推荐阅读
- powerbi - 在数据流中,当从表中删除列/行时,数据流(PRO 许可证、共享容量)是否刷新执行查询折叠?
- c - 管道之间的迭代通信
- javascript - 为什么我在浏览器上调整大小时页面会滚动?
- gitlab - 如何确保使用 GitLab CI 更改了文件?
- r - 我打开我的 R 控制台并收到此消息 - '错误:找不到函数“install.packages”'。我该如何解决?
- linux - 如何让 GDB 将我手工制作的可运行 ELF 文件识别为可执行文件?
- npm - 错误:子编译失败:找不到入口模块:错误:无法解析[文件路径]
- python - 如何在不使用拆分方法的情况下找到字符串中最长的单词
- python-3.x - DRF Serializer 在执行 serializer.data 时返回空字典
- nginx - Nginx 和 certbot 的 ERR_SSL_PROTOCOL_ERROR