簡體   English   中英

Firestore - 獲取文檔后如何獲取文檔 ID?

[英]Firestore - How to get document ID after fetching document?

在我的 Firestore 數據庫中,每個用戶都有一個名為 Apps 的子集合。 我想使用每個應用程序的 ID 創建子 URL。 但我不知道如何獲取我的 Apps 子集合的文檔 ID。 也許我必須使用onSnapshot()方法,但我不確定如何在我的情況下使用它。

謝謝你的幫助。

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();
        setApps(data.docs.map(doc => 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={}>
                  <EditOutlined />
                  <span> Edit the app </span>
                </Link>
              </Button>
            ]}
          >
            <Meta title={app.appName} description={app.description} />
          </Card>
        </Col>
      ))}
    </Row>
  );
}

您的data.docsDocumentSnapshot對象的數組。 每個都有一個帶有文檔 ID 的id屬性。 如果您想將其添加到您的 state,請嘗試以下操作:

setApps(data.docs.map(doc => { id: doc.id, ...doc.data()));

這應該在每個映射的 object 上創建一個屬性id ,以及使用 JavaScript 擴展運算符的其他字段的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM