【问题标题】:doc.data(); from firebase returns undefined but prints normally?doc.data(); from firebase 返回未定义但打印正常?
【发布时间】:2020-03-17 19:06:27
【问题描述】:

所以我需要从 firebase 集合中获取具有给定 ID 的数据。然后我的函数应该返回它(文档),并且在我的测试中它应该打印(作为“结果”)。出于某种原因,我的测试打印出“未定义”,但我的函数 (getIteration(id)) 准确地打印出我需要它返回的内容(在返回上方的 console.log 中)。为什么它返回 undefined 但使用相同的 doc.data() 打印我需要的内容?

这是我的代码:

//gets the iteration with the given id
async function getIteration(id) {
    fb.db.collection('iteration').where('id', '==', id).get().then(snapshot => {
        snapshot.forEach(doc => {
            console.log(doc.data())
            return doc.data();
        })
    })
}

和我的测试:

firebase.getIteration(fbIterationID).then(function(result){
 console.log('LOGGING FB ITERATION DOCUMENT WITH THE ID OF: ' + fbIterationID)
    console.log(result)
})

【问题讨论】:

    标签: javascript database firebase return undefined


    【解决方案1】:

    您需要从getIteration 返回承诺,以便调用者可以使用其结果。使函数异步不会为您做到这一点:

    async function getIteration(id) {
        return fb.db...
    }
    

    【讨论】:

    • 喜欢这个?这仍然给我未定义的:(async function getIteration(id) { return fb.db.collection('iteration').where('id', '==', id).get().then(snapshot => { snapshot.forEach(doc => { console.log(doc.data()) return doc.data(); }) }) }
    【解决方案2】:
        //gets the iteration with the given id
    async function getIteration(id) {
        return fb.db.collection('iteration').where('id', '==', id).get().then(snapshot => {
            return snapshot.docs.map(doc => doc.data());
        })
    }
    

    【讨论】:

    • 虽然此代码可能会为问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并将这些知识应用到他们自己的代码中。在解释代码时,您也可能会以赞成票的形式从用户那里获得积极的反馈。
    【解决方案3】:
    import React, {useEffect, useLayoutEffect, useState} from 'react'
    import {View, Text, StyleSheet, SafeAreaView, ScrollView, TouchableOpacity } from 'react-native'
    import { Avatar } from 'react-native-elements/dist/avatar/Avatar';
    import CustomListItem from '../../components/CustomListItem'
    import { auth, db } from '../../services/firebase';
    import {SimpleLineIcons} from '@expo/vector-icons'
    
    
    export default function HomeScreen({ navigation }) {
    
        const [chats, setChats] = useState([]);
        const [userInfo, setUserInfo] = useState([])
        const [isDms, setIsDms] = useState(true);
        
      
    
        
    
        useEffect(() => {
            function unsubscribeDms(){ 
                db.collection('chats').onSnapshot(snapshot => {
                snapshot.docs.map(doc => {
                    if (doc.data().isDM == true){
                        if (doc.data().users[0] == auth.currentUser.uid){
                            setChats(chats => [...chats, {id: doc.id, data: doc.data(), otherUser: doc.data().users[1]}])
    
                            db.collection("users").doc(doc.data().users[1]).get().then((doc) => {
                                setUserInfo(userInfo => [...userInfo, {uid: doc.id,  data: doc.data()}]
                                    )
                            
                                
                            })
                            
                        }
    
                        else if (doc.data().users[1] == auth.currentUser.uid){
                            
                            setChats(chats => [...chats, {id: doc.id, data: doc.data(), otherUser: doc.data().users[0]}])
    
                            db.collection("users").doc(doc.data().users[0]).get().then((doc) => {
                                setUserInfo(userInfo => [...userInfo, {uid: doc.id,  data: doc.data()}]
                                )
                            
                                
                            })
                        }
                    }
    
                })
    
    
                
            })}
    
    
            async function unsubscribeGcs(){
                await db.collection('chats').onSnapshot(snapshot => {
                    snapshot.docs.forEach(doc => {
                        if (doc.data().isDM == false){
                            var allUsers  = doc.data().users
                            if (allUsers.includes(auth.currentUser.uid)){
                                setChats(chats => [...chats, {id: doc.id, data: doc.data()}])
    
                            }
                        }
                    })
                })
            }
    
            if (isDms){
                unsubscribeDms()
    
            }
    
            else {
                unsubscribeGcs()
            }
    
            
    
            
    
        }, [])
    
        function getphotoUrl(uid){
    
            //return JSON.stringify(userInfo[0])
    
    
            return userInfo.length
    
    
            if (userInfo.length > 0){
                var picInfo = userInfo.filter((value) =>{
                    return value.uid == uid
                })[0].uid
                //})[0].data.photoURL
    
                
        
        
        
                
             
                return picInfo
    
            }
            else {
                return 'null'
            }
        }
    
        function getDisplayName(uid){
    
            //return JSON.stringify(userInfo[0])
    
            
            return userInfo.length
         
        
            if (userInfo.length > 0){
                var nameInfo = userInfo.filter((value) =>{
                    return value.uid == uid
                })[0].uid
                //})[0].data.displayName
    
    
                console.log("this is the display name" + nameInfo)
    
    
    
    
                return nameInfo
            }
            else {
                return 'null'
            }
    
    
        }
        
        
    
        function signOutUser(){
            auth.signOut().then(() => {
                navigation.replace('Login')
            })
        }
    
    
        
    
    
        useLayoutEffect(() => {
            navigation.setOptions({
                title: "Chats",          
    
                
    
                headerRight: () => (
                    <View style={{
                        flexDirection: "row",
                        justifyContent: "space-between",
                        width: 80,
                        marginRight: 20
    
                    }}>
                        
                    <View style={{marginLeft: 20}}>
                        <TouchableOpacity onPress={() => navigation.navigate("Profile", {currentUser: auth.currentUser})} activeOpacity={0.5}>
                            <Avatar rounded source={{ uri: auth?.currentUser?.photoURL }}/>
                        </TouchableOpacity>
                    </View>
    
                        <TouchableOpacity onPress={() => navigation.navigate("AddChat")}>
                            <SimpleLineIcons name="pencil" size={24} color="black"></SimpleLineIcons>
                        </TouchableOpacity>
    
                    </View>
                )
    
                
    
    
            });
        }, [navigation])
    
        function enterChat(id, chatName, photo){
            navigation.navigate("Chat", {
                id: id,
                chatName: chatName,
                photo: photo
    
            })
        }
    
        return (
            <SafeAreaView>
               
                <ScrollView style={styles.container}>
                    {chats.map(({id, data, otherUser}) => (
                        <CustomListItem key={id} id={id} enterChat={enterChat} photo={getphotoUrl(otherUser)} userName={getDisplayName(otherUser)} isDm={data.isDM}/>
                    ))}
                </ScrollView>
            </SafeAreaView>
        )
    }
    
    const styles = StyleSheet.create({
        container: {
            height: "100%"
        }
    
    })
    

    【讨论】:

      猜你喜欢
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      相关资源
      最近更新 更多