gpt4 book ai didi

javascript - 如何在 React 中获取 Firestore 的文档 ID

转载 作者:行者123 更新时间:2023-12-05 00:55:42 25 4
gpt4 key购买 nike

这是我的 Firestore 数据库: enter image description hereuseEffect() 更新了锻炼常量后,我只能访问名称和 uId。我如何也可以访问文档 ID?

import React, { useState, useEffect } from "react";
import "./Workouts.sass";
import Workout from "./Workout";
import firebase from "./firebase";

function Workouts() {
const [workouts, setWorkouts] = useState([]);

useEffect(() => {
let user = firebase.auth().currentUser;
const database = firebase.firestore();
const unsubscribe = database
.collection("workouts")
.where("uId", "==", user.uid)
.onSnapshot((snapshot) => {
setWorkouts(snapshot.docs.map((doc) => doc.data()));
});

return () => {
unsubscribe();
};
}, []);

return (
<div className="Workouts">
{workouts.map((workout) => (
<Workout key={workout.name} workout={workout} />
))}
</div>
);
}

export default Workouts;

最佳答案

您可以使用快照 doc.id
我喜欢将 id 作为属性添加到对象:

snapshot.docs.map((doc) => ({id: doc.id, ...doc.data()}))

关于javascript - 如何在 React 中获取 Firestore 的文档 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63671237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com