使用 React Native 在平面列表中 Firestore 数据

Firestore data in a flatlist with react native

我一直在尝试将数据从我的 Firestore 数据库输出到 React native 中的 Flatlist,但到目前为止没有成功。

我使用这个 Flatlist for RN and Firestore docs 作为入门参考,但出于某种原因,我在这里遗漏了一些关于 Flatlist 输出方法的内容,因为它不会输出 flatlist 本身。当我控制台记录位置数组时,它向我显示了我查询过的所有文档,因此它确实将它们全部推送到一个数组中,我的理解是 FlatLists 它们需要一个数组才能运行,但它不会抛出任何错误,只是不会'渲染。欢迎任何帮助!


    useEffect(async () => {
        const locations = [];
        const querySnapshot = await getDocs(collection(db, "Location"));
        querySnapshot.forEach((doc) => {
          // doc.data() is never undefined for query doc snapshots
            locations.push(doc.data());
          console.log(locations);
        }); 
        return () => querySnapshot();
    }, []);
    

    return (
        <View style={styles.screen}>
            <Text>hello</Text>
            <FlatList data={locations}
                renderItem={({ item }) => (
                    <View >
                        <Text>name: {item.name}</Text>
                        <Text>Depth: {item.depth}m</Text>
                        <Text>GeoLocation: {item.geo}</Text>
                        <Text>id: {item.uid}</Text>
                    </View>
                )}
            />

您的变量 locations 在您的 useEffect 中定义。 FlatList 无法访问它。您需要通过 useState 创建一个 state 并在加载数据后将其存储在那里。设置 state 将导致组件重新渲染,并且 FlatList 将使用新数据进行更新。

这是一种可能的实现方式。

const SomeScreen = () => {

    const [locations, setLocations] = useState([])

    useEffect(() => {
        const loadData = async () => {
            const querySnapshot = await getDocs(collection(db, "Location"));
            setLocations(querySnapshot.map(doc => doc.data()))
        }

        loadData()
    }, [setLocations]);
    

    return (
            <FlatList data={locations}
                renderItem={({ item }) => (
                    ...
                )}
            />
   )
}