[英]How to return data from Firestore query to a FlatList
我是 React-Native 的新手,我正在尝试将数据数组从 firstore 查询返回到我可以设置设备的设备屏幕。 我使用 .get() 和 .then() 进行了这项工作,但我没有得到更新的事件,所以我已经转移到 onSnapshot 并且似乎在查询结束时有数据,但无法在屏幕。
import React, { useEffect, useRef, useState } from "react";
import { Alert,FlatList,RefreshControl,StatusBar,Text,View } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import styles from "./styles";
import { getDevices } from "../../services/devices";
import { useNavigation } from "@react-navigation/native";
import { Feather } from "@expo/vector-icons";
import CircularProgress from "react-native-circular-progress-indicator";
import { removeDevice } from "../../redux/actions";
import { useDispatch } from "react-redux";
import firebase from "firebase/app";
import "firebase/firestore";
const wait = (timeout) => {
return new Promise((resolve) => setTimeout(resolve, timeout));
};
export default function DevicesScreen() {
const [devices, setDevices] = useState([]);
const [loading, setLoading] = useState(false);
const componentMounted = useRef(true);
const navigation = useNavigation();
useEffect(() => {
getDevices().then(setDevices)
},[]);
console.log()
TypeError: undefined is not an object (evaluating '(0, _devices.getDevices)().then')
This error is located at:
in DevicesScreen (created by SceneView)
出现此错误。 如果我 remove.then(setDevices) 我可以在 console.log 上看到数据数组
import firebase from "firebase/app";
import "firebase/firestore";
export const getDevices = () => {
firebase
.firestore()
.collection("device")
.where("user_id", "==", "Rweeff9MO8XIDheZLx0HVbfaezy2")
.get()
.then((querySnapshot) => {
querySnapshot.docs.map(doc => {
let data =doc.data();
console.log(data);
return { id, ...doc };
}
)}
)
}
谢谢
您的代码中有几个问题。
id
未定义。 你需要做doc.id
。所以以下应该可以解决问题:
export const getDevices = () => {
return admin // <========= See the return here
.firestore()
.collection("projects")
.get()
.then((querySnapshot) => {
return querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
// ^^^ See the return here
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.