我使用 Firebase 作為后端,架構如下
const sample_data = {
Name: "",
Address: "",
Contact_no: "",
Email: "",
img_url: ""
}
首先,我正在使用這樣的async功能獲取
獲取串列.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;
然后我像這樣將檢索到的資料傳遞給我的卡片組件。
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 組件。
卡.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;
uj5u.com熱心網友回復:
FetchList不是 React 組件。您應該useEffect在組件掛載時(或按需按需)從 React 組件生命周期方法或鉤子中獲取資料。
匯出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>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/338015.html
標籤:javascript 反应 异步等待 反应道具
上一篇:轉換字串陣列時保留引號
