繁体   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

使用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]);

属性列表.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;

我认为这可能是因为在 PropertyList.jsx 页面将数据状态调用到 map 函数之后,将 API 提取到 res 变量中

** API 输出:** [ { "type": "hotel", "count": 6 }, { "type": "apartments", "count": 0 }, { "type": "resort", “计数”:0 },{“类型”:“别墅”,“计数”:0 },{“类型”:“小屋”,“计数”:0 }]

你知道这个错误背后的原因是什么吗?

res.data,API响应中缺少data key,所以这种情况需要添加条件

条件是——

const res = 等待 axios.get(url); 设置数据(res.data);

S/B

const res = 等待 axios.get(url);

常量数据=(res.data!==未定义)? 资源数据:[];

设置数据(数据);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM