如何使用React Native显示来自Firestore的数据

时间:2020-07-10 22:57:27

标签: reactjs firebase react-native google-cloud-firestore

我正在尝试在主页上显示来自Firestore的数据,但似乎无法正常工作。我想显示集合中的所有数据。该集合包括名称,ID,位置等...

    import Firebase from "./lib/firebase";
import { useEffect, useState } from "react";
import { SnapshotViewIOS } from "react-native";
// export async function getRestaurants(restaurantsRetrieved) {
//   var restaurantList = [];

//   var snapshot = await firebase.firestore().collection("Restaurants").get();

//   snapshot.forEach((doc) => {
//     restaurantList.push(doc.data());
//   });

//   restauantsRetrieved(restaurantList);
// }
export default () => {
  const [restaurantsList, setRestaurantsList] = useState([]); //Initialise restaurant list with setter
  const [errorMessage, setErrorMessage] = useState("");

  const getRestaurants = async () => {
    try {
      const list = [];
      var snapshot = await Firebase.firestore().collection("Restaurants").get();
      console.log("Here");
      snapshot.forEach((doc) => {
        list.push(doc.data());
      });
      setRestaurantsList(list);
    } catch (e) {
      setErrorMessage(
        "There's nae bleeding restaurants, I told you to upload them!"
      );
    }
  };

  //Call when component is rendered
  useEffect(() => {
    getRestaurants();
  }, []);

  return (

  <View style={tailwind('py-10 px-5')}>
    <Text style={tailwind('text-4xl font-bold')}>
      {restaurantsList}
    </Text>
};

1 个答案:

答案 0 :(得分:0)

国家并没有更新,因为它只是参考了清单。因此,您需要更新下面的类似代码

.....

setRestaurantsList([...list]);

......