reactjs 从React js中的实时Firestore数据库中提取数据的问题

rmbxnbpk  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(104)

我有一些问题,从firebase实时数据库中获取数据。
我想获取的数据结构如下所示:
enter image description here
下面是我的示例代码:

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;

一切工作如预期,我面临的唯一问题是,每当我访问“参与者”我得到以下错误:

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)

先谢谢你。
我希望参与者的名字会显示在显示器上。因为数据存在并且没有未定义。

laik7k3q

laik7k3q1#

在这里用[]初始化event

const [event, setEvent] = useState([]);

但随后您可以在渲染代码中使用它:

<h2>Name: {event.Particpants[0].Name}</h2>

因为你用[]初始化event,它没有Particpants属性,也没有[0]
在渲染event之前,您需要确保它有一个非空的Participants数组。

<h2>Name: {event.Participants && event.Participants.length ? event.Participants[0].Name : "Loading..."}</h2>

相关问题