【发布时间】:2021-10-28 20:49:11
【问题描述】:
我使用Firebase 作为后端,架构如下
const sample_data = {
Name: "",
Address: "",
Contact_no: "",
Email: "",
img_url: ""
}
首先,我使用 asyncfunction 这样的函数获取
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 组件中作为道具传递的所有数据,但是当我在这里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.js中的getItems();更改为await getItems();,这样行吗? -
不,它肯定会抛出一个错误,因为在
async函数之外调用了getItems()。所以 await 不起作用 -
FetchList不是 React 组件。当组件挂载(或按需)时,您应该从 React 组件生命周期方法或useEffect挂钩中获取数据。 -
我试过
useEffect仍然无法达到理想的解决方案:(你能说出你的答案吗:) -
导出
getItems函数在ListHospitals组件中创建一个状态> 在ListHospitals组件中创建另一个async function以调用您的getItem函数并将其设置为状态。在useEffect中调用新函数。不要通过道具将对象作为children传递。用另一个道具名称传递它。
标签: javascript reactjs async-await react-props