从数据库中获取后如何传递道具?

How can I pass props after fetching from database?

我正在使用 Firebase 作为后端,架构如下

const sample_data = {
  Name: "",
  Address: "",
  Contact_no: "",
  Email: "",
  img_url: ""
}

首先,我正在使用这样的async函数获取

FetchList.js


let dummy = {}

async function getItems(){
    const response = await fetch('realtime__database__of__firebase__url');
    
    if (!response.ok) {
        throw new Error("Something went wrong");
      }
  
      dummy = await response.json();
}
getItems();
export default dummy;

然后我将检索到的数据像这样传递到我的 card 组件。

ListHospital.js

import Card from "../UI/Card";
import dummy from "./FetchList";


const ListHospitals = () => {
    return <Card>
        {dummy}
    </Card>
}

export default ListHospitals;

最后我想访问我在 CARD 组件中作为 props 传递的所有数据,但是当我 console.log 这里的输出是 undefined 而当我 console.log 获取数据后,它会提供合适的输出。 我遇到的问题是在获取数据之前正在导出 FetchList 组件。

Card.js

import classes from "./Card.module.css";


const Card = (props) => {

    let url = props.children.img;
    console.log(url);
    return <div>
                <img src={props.children.img} alt={props.children.Name}></img>

                <h1 >{props.children.Name}</h1>
                <p>{props.children.Address}</p>
                <h3 >Contact</h3>
                <p>{props.children.Email}</p>
                <p>{props.children.Contact_no}</p>

</div>
}

export default Card;

FetchList 不是 React 组件。您应该在组件安装时从 React 组件生命周期方法或 useEffect 挂钩中获取数据( 或根据需要按需 )。

导出getItems函数:

async function getItems(){
  const response = await fetch('realtime__database__of__firebase__url');
    
  if (!response.ok) {
    throw new Error("Something went wrong");
  }
  
  return response.json();
}

export default getItems;

安装组件时加载。将 data 作为道具传递给 Card 而不是 children.

import { useEffect, useState } from 'react';
import Card from "../UI/Card";
import getItems from "./FetchList";

const ListHospitals = () => {
  const [data, setData] = useState({});

  useEffect(() => {
    getItems()
      .then(data => setData(data))
      .catch(error => {
        // fetch can return rejected Promise, maybe handle it?
      });
  }, []);

  return <Card data={data} />;
}

卡 - 访问 data 道具。

const Card = ({ data }) => {
  const url = data.img;
  console.log(url);

  return (
    <div>
      <img src={data.img} alt={data.Name} />
      <h1 >{data.Name}</h1>
      <p>{data.Address}</p>
      <h3>Contact</h3>
      <p>{data.Email}</p>
      <p>{data.Contact_no}</p>
    </div>
  );
}