[英]I am not able to retrive my data from api showing error " Cannot read properties of undefined " ,sometime i recieve data and most of the time i don't
useFetch.js使用Fetch.js
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const res = await axios.get(url);
setData(res.data);
} catch (err) {
setError(err);
}
setLoading(false);
};
fetchData();
}, [url]);
PropertyList.jsx属性列表.jsx
import React from "react";
import useFetch from "../../hooks/useFetch";
import "./propertyList.css";
function PropertyList() {
const { data, loading, error } = useFetch(
"http://localhost:3000/api/hotels/countByType"
);
console.log(data);
const images = [
"https://media-cdn.tripadvisor.com/media/photo-s/1c/d3/b2/4f/exterior-view.jpg",
"https://www.phillyaptrentals.com/wp-content/uploads/2020/12/apartment-building-what-makes-good-apartment-building-scaled.jpg",
"https://dynamic-media-cdn.tripadvisor.com/media/photo-o/1a/01/04/c9/manduna-resort.jpg?w=900&h=-1&s=1",
"https://images.squarespace-cdn.com/content/v1/585562bcbe659442d503893f/c3b765c0-45e3-46b3-9ff9-b4101fb30674/01.+Exotik+Villas+Bali+-+Aloui.jpg",
"https://vancouverisland.travel/app/uploads/2021/04/wood-cabin-on-vancouver-island_BenGiesbrecht.jpg",
];
return (
<div className="pList">
{loading ? (
"Loading.."
) : (
<>
{data &&
images.map((img, i) => (
<div className="pListItem" key={i}>
<img src={img} alt="" className="pListImg" />
<div className="pListTitles">
<h1>{data[i].type}</h1>
<h2>
{data[i].count} {data[i].type}
</h2>
</div>
</div>
))}
</>
)}
</div>
);
}
export default PropertyList;
I think this may be because of fetching API into the res variable after PropertyList.jsx page calls the data state into the map function我认为这可能是因为在 PropertyList.jsx 页面将数据状态调用到 map 函数之后,将 API 提取到 res 变量中
**output of API : ** [ { "type": "hotel", "count": 6 }, { "type": "apartments", "count": 0 }, { "type": "resort", "count": 0 }, { "type": "villas", "count": 0 }, { "type": "cabins", "count": 0 } ] ** API 输出:** [ { "type": "hotel", "count": 6 }, { "type": "apartments", "count": 0 }, { "type": "resort", “计数”:0 },{“类型”:“别墅”,“计数”:0 },{“类型”:“小屋”,“计数”:0 }]
Do you know what's the reason behind this error?你知道这个错误背后的原因是什么吗?
res.data, data key is missing in API response, so in this case you need to add conditions res.data,API响应中缺少data key,所以这种情况需要添加条件
The conditions is -条件是——
const res = await axios.get(url); const res = 等待 axios.get(url); setData(res.data);
设置数据(res.data);
S/B S/B
const res = await axios.get(url); const res = 等待 axios.get(url);
const data = (res.data !== undefined) ?常量数据=(res.data!==未定义)? res.data : [];
资源数据:[];
setData(data);设置数据(数据);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.