【发布时间】:2021-10-28 20:48:37
【问题描述】:
我正在做一个项目,其中我的数据库中的数据是这样的:
我不明白我做错了什么!这是我的 FetchList.js
import { useState } from "react";
const FetchList = async()=>{
const[data, setData] = useState()
const response = await fetch('https://__firebase__url__');
if (!response.ok) {
throw new Error("Something went wrong");
}
let responseData = await response.json();
const loadedHospitals = [];
for (const key in responseData){
loadedHospitals.push({
key: responseData[key].key,
Name: responseData[key].Name,
Email: responseData[key].Email,
Contact_no: responseData[key].Contact_no,
img: responseData[key].img,
});
}
setData(loadedHospitals);
const hospitals = data.map(hospital => {
console.log(hospital);
});
return data;
}
export default FetchList;
我想将数组中的整个结果传递给 ListHospital.js,然后将其与 Card 组件进行映射。
import Card from "../UI/Card";
import FetchList from "./FetchList";
import { useState, useEffect } from "react";
const ListHospitals = () => {
const [data, setData] = useState();
useEffect(() => {
FetchList().then(data => setData(data));
}, []);
return data.map((item)=><Card>{item}</Card>);
}
export default ListHospitals;
错误:
TypeError: Cannot read properties of undefined (reading 'map')
【问题讨论】:
-
你有什么问题?
-
TypeError: data.map 不是函数@emkarachchi
-
useState({})有一个对象而不是数组 -
是的,现在错误是
TypeError: Cannot read properties of undefined (reading 'map') -
认为您需要从
FetchList返回数据。尝试添加return loadedHospitals
标签: reactjs async-await react-props