[英]Issue with fetchin data from Realtime Database in React js
I have some issue with fetching the data from firebase live database.我在从 firebase 实时数据库中获取数据时遇到了一些问题。
The datastructure which i want to fetch looks like that:我想要获取的数据结构如下所示:
enter image description here在此处输入图像描述
Here is my sample code:这是我的示例代码:
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { getDatabase, ref, set, onValue } from "firebase/database";
import { db } from "../utils/firebase";
const ClientDetailLive = (props) => {
const params = useParams();
const { userID } = useParams();
const { eventID } = useParams();
const { participantID } = useParams();
const [event, setEvent] = useState([]);
const [participant, setParticipants] = useState("");
useEffect(() => {
const dbRef = ref(
db,
"myPath"
);
onValue(dbRef, (snapshot) => {
const data = snapshot.val();
console.log(data);
setEvent(data);
}, []);
return (
<>
Client stuff: {JSON.stringify(params)}
<h1></h1>
UserID: {userID}
<h1></h1>
Event: {eventID}
<h1></h1>
Participant: {participantID}
<div key={event.id}>
<h2>Event Name: {event.Title}</h2>
<h2>Datum: {Date(event.Time)}</h2>
</div>{" "}
<h1>"Ihre Daten"</h1>
<h2>Name: {event.Particpants[0].Name}</h2>
</>
);
};
export default ClientDetailLive;
Everything works like expected, the only issue Iam facing is, whenever iam accessing the "Participants" i get follwoing error:一切都按预期进行,我面临的唯一问题是,每当我访问“参与者”时,我都会收到以下错误:
ClientDetailLive.js:85 Uncaught TypeError: Cannot read properties of undefined (reading '0')
at ClientDetailLive (ClientDetailLive.js:85:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
Thank you in advance.先感谢您。
I would expect that the participant name will be shown on the display.我希望参与者姓名会显示在显示屏上。 Since the data exists and is not undefined.由于数据存在并且不是未定义的。
You initialize event
with []
here:您在此处使用[]
初始化event
:
const [event, setEvent] = useState([]);
But then you use it in the rendering code with:但是随后您在渲染代码中使用它:
<h2>Name: {event.Particpants[0].Name}</h2>
Since you initialize event
with []
, it doesn't have a Particpants
property and there's no [0]
on it.由于您使用[]
初始化event
,因此它没有Particpants
属性并且上面没有[0]
。
You'll want to ensure that event
has a non-empty Participants
array before rendering it.在呈现事件之前,您需要确保该event
具有非空的Participants
数组。 Something like:就像是:
<h2>Name: {event.Participants && event.Participants.length ? event.Participants[0].Name : "Loading..."}</h2>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.