firebase - React Native - Firestore 等待渲染直到查询结束
问题描述
我使用 react native 和 firestore 制作应用程序。这是我的一段代码;
getData(mat){
let count = 0;
let val;
db.collection("Yemek").doc("Materials").collection(mat).get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
count++;
val = doc.data().value;
matKey = mat+count.toString();
this.state.array.push([
meal=mat, value=val, status=false, key=matKey
]);
});
}).catch(err => {
console.log('Error getting documents', err);
return false;
});
}
componentWillMount(){
this.getData('vegetables');
this.getData('legumes');
this.getData('meat');
this.getData('milk');
this.getData('others');
}
render() {
return (//Render components)}
我正在渲染具有位于状态的数组的组件。但它返回 null 因为在查询结束之前应用程序渲染组件。我昨天搜了一下。我想我应该使用承诺,但我不明白这一点。你可以帮帮我吗?
解决方案
通常推荐的方法是使用状态。在您的构造函数中,初始化您的状态,并设置一个布尔值(例如“正在加载”)以指示您的页面正在加载。加载完成后,将加载值设置为 false 以指示加载完成。这将导致您的课程重新渲染。
为了一致性,您可以使用条件渲染;如果页面仍在加载,则显示活动指示器,否则显示您的页面内容。这两个项目在这里和其他地方都有很好的例子。
推荐阅读
- python - find-s 算法的输出
- google-cloud-platform - 为什么授予“allAuthenticatedUsers”成员“Cloud Functions Invoker”角色不适用于谷歌云功能?
- powerbi - Powerbi oauth api 在从访问令牌访问数据时提供 403
- google-sheets - SAAS 应用程序的 Google 表格 API 限制
- java - 直接在Eclipse中运行源码就可以了。为什么 Jar 文件将停止运行并且控制台中没有异常显示?
- c# - 即使没有关注表单应用程序,也继续运行 ProcessCmdKey
- python-3.x - 猪拉丁函数代码列表中的值错误。当 x 明显在列表中时,删除(x)x 不在列表中
- .net - 如何将 XmlDocument 保存到“格式类似于 Visual Studio”的 .csproj 中,其中空元素保存在单独的行中?
- java - 给定一个数字数组,返回所有其他数字的乘积数组(带除法)
- arrays - 具有最小可能交换的相对排序