[英]Firestore - How can I add the Document ID and their data in my state?
In my database from Firestore, each User has a sub-collection called Apps.在我的 Firestore 数据库中,每个用户都有一个名为 Apps 的子集合。 I need to add in my state the id of each document and their data.
我需要在我的 state 中添加每个文档的 ID 及其数据。 I know how to add the data in my state, with the following code
setApps(data.docs.map(doc => doc.data()))
and I know how to get the ID of each document data.docs.map(doc => console.log(doc.id, doc.data()))
.我知道如何在我的 state 中添加数据,使用以下代码
setApps(data.docs.map(doc => doc.data()))
并且我知道如何获取每个文档data.docs.map(doc => console.log(doc.id, doc.data()))
。
But how can I add in my state doc.id
and doc.data()
at the same time?但是如何同时添加我的 state
doc.id
和doc.data()
?
Thanks for your help.谢谢你的帮助。
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> ); }
I finally found the solution我终于找到了解决方案
setApps(data.docs.map(doc => {return {...doc.data(), id: doc.id} }));
Besides that, you can add this if you use setState除此之外,如果你使用 setState,你可以添加这个
initialData.forEach((doc) => {
this.setState({
data: [...this.state.data,{...doc.data(), id: doc.id }],
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.