【问题标题】:How can i get specific user data from firestore in React? [duplicate]如何从 React 中的 firestore 获取特定的用户数据? [复制]
【发布时间】:2021-03-31 21:54:57
【问题描述】:

所以问题是,当我尝试使用 forEach 函数获取详细信息时,它会为我提供所有用户的详细信息,这些详细信息可在 firestore 上找到。让我用代码解释一下:

这是我在个人资料页面中获取详细信息的代码:

import React from 'react';
import firebase from 'firebase';

const firestore = firebase.firestore();

class ProfilePage extends React.Component {
    state = {
        profiledata : null
    }

    componentDidMount(){
        firestore.collection('profiledata')
            // .doc("JgT2LyOB4jqhMv9YMgrh")
            .get()
            
             .then((snapshot) => {
                const profiledata  = []
                snapshot.forEach(function(doc){
                    const data = doc.data();
                    profiledata.push(data);
                }
                )
                this.setState({profiledata :  profiledata})
                })
                }
             
            render(){
        return(
            <div className='profile'>
                <h1>User</h1>
                {
                    this.state.profiledata && 
                        this.state.profiledata.map( profiledata => {
                            return(
                                <div>
                                    <p>
                                        First Name : {String(profiledata.firstname)}
                                        Last Name : {String(profiledata.lastname)}
                                        Company Name : {String(profiledata.companyname)}
                                                                        
                                        </p>
                                </div>
                                
                            )
                        })
                }
                </div>
        )
    }export default ProfilePage;

【问题讨论】:

  • 您正在阅读整个profiledata 集合,因此获取所有用户的个人资料数据是有意义的。如果取消注释 ` // .doc("JgT2LyOB4jqhMv9YMgrh")` 会发生什么?

标签: reactjs firebase google-cloud-firestore


【解决方案1】:

正如 Frank 在 cmets 中提到的,您正在查询整个集合 profileData 而不引用特定文档或对其进行过滤,因此预期结果是获得所有用户,这正是您所获得的。

为了获取特定文档,正如您在此 documentation 中看到的,您必须在与 .doc() 的通话中引用 documentId,就像您显然在注释掉的部分中所做的那样,所以如果您这样做:

firestore.collection('profiledata')
         .doc("JgT2LyOB4jqhMv9YMgrh")
         .get()

如果存在,您应该获取 ID 为 JgT2LyOB4jqhMv9YMgrh 的用户。

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 2020-01-14
    • 2022-11-24
    • 2020-03-29
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多