英文:
Get a single doc inside subcollection by Id
问题
以下是您要翻译的代码部分:
[![enter image description here][1]][1]
How can i get a single document data inside a subcollection by his id so i can show just a single workout info inside a component?
export default function WorkoutInfo(props){
const [workout,setWorkout]=useState({});
const [workoutName,setWorkoutName] = useState("");
const workoutsCollectionRef = collection(db,"users",props.userId,"workouts");
useEffect(()=>{
const queryWorkouts = query(workoutsCollectionRef)
const unsuscribe= onSnapshot(queryWorkouts,(snapshot)=>{
let workout={};
snapshot.forEach((doc)=>{
if(doc.id==props.workotId)
workout=({...doc.data(),id:doc.id});
})
setWorkout(workout);
})
return () => unsuscribe();
},[])}
在此提供了代码的中文翻译。
英文:
How can i get a single document data inside a subcollection by his id so i can show just a single workout info inside a component?
export default function WorkoutInfo(props){
const [workout,setWorkout]=useState({});
const [workoutName,setWorkoutName] = useState("");
const workoutsCollectionRef = collection(db,"users",props.userId,"workouts");
useEffect(()=>{
const queryWorkouts = query(workoutsCollectionRef)
const unsuscribe= onSnapshot(queryWorkouts,(snapshot)=>{
let workout={};
snapshot.forEach((doc)=>{
if(doc.id==props.workotId)
workout=({...doc.data(),id:doc.id});
})
setWorkout(workout);
})
return () => unsuscribe();
},[])}
What's wrong with this code?
答案1
得分: 0
如果props.workotId
是您想要加载的训练文档的文档ID,您可以使用以下方式进行监听:
useEffect(() => {
const documentRef = doc(workoutsCollectionRef, props.workotId);
const unsubcribe = onSnapshot(documentRef, (doc) => {
setWorkout({...doc.data(), id: doc.id});
})
return () => unsubcribe();
}, [])
英文:
If props.workotId
[sic] is the the document ID of the workout document you want to load, you can listen to it with:
useEffect(()=>{
const documentRef = doc(workoutsCollectionRef, props.workotId);
const unsubcribe= onSnapshot(documentRef,(doc)=>{
setWorkout({...doc.data(),id:doc.id});
})
return () => unsubcribe();
},[])}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论