简体   繁体   English

我无法从显示错误“无法读取未定义的属性”的 api 中检索我的数据,有时我会收到数据,而大多数时候我没有

[英]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.

相关问题 我收到此错误:TypeError:每当我执行命令时都无法读取未定义的属性(读取“成员”) - i recieve this error: TypeError: Cannot read properties of undefined (reading 'members') whenever i execute command 我收到此错误 TypeError: Cannot read properties of undefined (reading 'header'), I am trying to middleware to get users data - I am getting this error TypeError: Cannot read properties of undefined (reading 'header') , I am trying to middleware to get users data 我正在尝试从 mongodb 连接我的 server.js express api 但它显示一些错误我不明白 - I am trying to connect my server.js express api from mongodb but it showing some error i don't understand it 我可以成功地从 API 中获取数据。 我可以读取一些属性,但尝试读取错误中的大部分结果 - I can fetch the data from an API in react succesfuly. I can read some of the properties but trying to read most of the results in erros 我无法读取图像。 它显示以下错误 - I am not able to read the image. It's showing the following error 我在 axios 补丁 api 中收到“Uncaught (in promise) TypeError: Cannot read property 'data' of undefined”错误 - I'm getting “Uncaught (in promise) TypeError: Cannot read property 'data' of undefined” error in axios patch api 为什么我不在 POST 读取数据 - Why i don't read data at POST 我正在尝试使用 axios 从我的后端获取数据,但它显示网络错误 - I am trying to get data from my backend using axios, but its showing Network error 不是重大错误,但我收到“TypeError:无法读取未定义的属性”。 我不确定我的下一步行动是什么 - Not a major error but I am getting `TypeError: Cannot read property 'has' of undefined`. I am not sure what my next move will be 我收到错误 Typerror 无法读取未定义的属性“执行” - I am getting an error Typerror Cannot read property 'execute' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM