繁体   English   中英

React 中的 API 调用“TypeError:无法读取未定义的属性(读取'map')”

[英]API call in React "TypeError: Cannot read properties of undefined (reading 'map')"

我正在尝试使用通过 API 调用检索到的数组中的数据填充对象列表。 我确实得到了正确的数据(可以 console.log 对象),但在代码中使用它不起作用。 我尝试了多种解决方案,但到目前为止没有任何效果,我被卡住了,然后又花了 2 天的时间寻求您的帮助。 我确信这是我还没有学过的简单的东西。

TypeError:无法读取未定义的属性(读取“地图”)

const EventCarousel = () => {
  const [data, setData] = useState([]);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    axios

      .get(
        "https://cdn.contentful.com/spaces/qqdjjpwbe10z/environments/master/entries?access_token=PRIVATE_TOKEN"
      )
      .then((res) => {
        console.log(res.data.items[0].fields.imageUrl);
        setData(res.data);
      })
      .catch((error) => {
        setError(error.message);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

if (loading) {
    return <p>Data is loading...</p>;
  } else
    return (

 {data.items.map((item) => (
            <div>
              <Event
                imageUrl={item.fields.imageUrl}
                title={item.fields.title}
                text={item.fields.text}
                linkUrl={item.fields.linkURL}
                location={item.fields.location}
                date={item.fields.date}
              />
            </div>
          ))}

JSON 结构如下所示:

{
"sys": {},
"total": 2,
"skip": 0,
"limit": 100,
"items": [
{
"metadata": {},
"sys": {},
"fields": {
"title": "Second Event",
"text": "This is decription of a second event",
"imageUrl": "https://i.imgur.com/ULO8mVt.png",
"linkUrl": "https://www.moabit.world",
"location": "Second Location",
"date": "second date"
}
},
{
"metadata": {},
"sys": {},
"fields": {
"title": "First Event",
"text": "This is first fetched text",
"imageUrl": "https://i.imgur.com/ULO8mVt.png",
"linkUrl": "https://www.facebook.com",
"location": "First location",
"date": "First date"
}
}
]
}

谢谢你

这是因为当您的组件被挂载时,它没有 data.items 字段,因为您的初始数据将是[]

您需要先将初始状态设置为包含{} ,然后更新data.items以有条件地运行。

尝试以下解决方案:

const EventCarousel = () => {
  const [data, setData] = useState({});
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    axios

      .get(
        "https://cdn.contentful.com/spaces/qqdjjpwbe10z/environments/master/entries?access_token=PRIVATE_TOKEN"
      )
      .then((res) => {
        console.log(res.data.items[0].fields.imageUrl);
        setData(res.data);
      })
      .catch((error) => {
        setError(error.message);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

if (loading) {
    return <p>Data is loading...</p>;
  } else
    return (

 {data?.items?.length ? data.items.map((item) => (
            <div>
              <Event
                imageUrl={item.fields.imageUrl}
                title={item.fields.title}
                text={item.fields.text}
                linkUrl={item.fields.linkURL}
                location={item.fields.location}
                date={item.fields.date}
              />
            </div>
          )) : null}

您将状态初始化为数组useState([])但将其用作对象data.items ,请选择其中一个:

const [data, setData] = useState({items: []});
setData(res.data)

// Or
const [data, setData] = useState([]);
setData(res.data.items)

暂无
暂无

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

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