首页 > 解决方案 > 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 因为在查询结束之前应用程序渲染组件。我昨天搜了一下。我想我应该使用承诺,但我不明白这一点。你可以帮帮我吗?

标签: firebasereact-nativegoogle-cloud-firestoreexpo

解决方案


通常推荐的方法是使用状态。在您的构造函数中,初始化您的状态,并设置一个布尔值(例如“正在加载”)以指示您的页面正在加载。加载完成后,将加载值设置为 false 以指示加载完成。这将导致您的课程重新渲染。

为了一致性,您可以使用条件渲染;如果页面仍在加载,则显示活动指示器,否则显示您的页面内容。这两个项目在这里和其他地方都有很好的例子。


推荐阅读