Firestore - 如何在我的州添加文档 ID 及其数据?

rkh*_*han 3 javascript node.js firebase reactjs google-cloud-firestore

在我的 Firestore 数据库中,每个用户都有一个名为“应用程序”的子集合。我需要在我的状态中添加每个文档的 ID 及其数据。我知道如何使用以下代码在我的状态中添加数据,setApps(data.docs.map(doc => doc.data()))并且我知道如何获取每个文档的 ID data.docs.map(doc => console.log(doc.id, doc.data()))

doc.id但我怎样才能同时添加我的状态doc.data()呢?

感谢您的帮助。

function AppList() {
   
    const [apps, setApps] = React.useState([])

    React.useEffect(() => {
        const fetchData = async () => {
            const db = firebase.firestore()
            var user = firebase.auth().currentUser;

            if (user != null) {
                var uid = user.uid
                const data = await db
                .collection('Users').doc(uid)
                .collection('Apps').get()
                
                //Add the data of each doc in my state
                setApps(data.docs.map( doc => doc.data()));
    
                //Get the document ID
                data.docs.map(doc => 
                    console.log(doc.id, '=>', doc.data())
                );
            }
        }
        fetchData()
    }, [])

    return (
        <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}> 
        {apps.map(app => (
            <Col className="gutter-row" span={100}>
                <Card
                style={{ width: 300, marginTop: 16}}
                actions={[
                    <Button type="default" size='middle'>
                    <Link to={app.appName}>    
                        <EditOutlined /> 
                        <span> Edit the app </span>
                    </Link>
                    </Button>,
                    ]}>
                    <Meta
                    title= {app.appName}
                    description={app.description}
                    />
                </Card>   
            </Col>
        ))}
        </ Row>  
    );
}
Run Code Online (Sandbox Code Playgroud)

rkh*_*han 6

我终于找到了解决方案

setApps(data.docs.map(doc => {return {...doc.data(), id: doc.id} }));
Run Code Online (Sandbox Code Playgroud)