You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React请求Flickr API报users.map is not a function错误及id提取咨询

问题解答

原users.map is not a function报错根因

你初始化users状态时默认值是空数组,但调用setUsers时传入的是接口返回的完整对象,此时users的类型从数组变为对象,而对象本身没有数组的map方法,所以触发报错。你修改为users.photos.photo.map的方案是正确的,因为photos下的photo字段才是你需要遍历的数组类型数据。

打印photo的id实现方案

方案1:接口请求成功后批量打印所有photo的id

修改getUsers方法即可:

const getUsers = async () => {
  const response = await fetch(
    "https://www.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=XXXXXXXXXXXXXXXXXXXXX&format=json&nojsoncallback=1"
  );
  const resData = await response.json();
  setUsers(resData);
  // 批量打印所有photo的id
  resData.photos.photo.forEach(photoItem => {
    console.log('photo id:', photoItem.id);
  })
};

方案2:遍历渲染时打印每个photo的id

直接在map的回调逻辑中添加打印语句即可:

{users.photos.photo.map((curElem) => {
  // 打印当前遍历到的photo的id
  console.log('当前photo的id:', curElem.id);
  return (
    <img
      src="https://www.thisislocallondon.co.uk/resources/images/12088462.jpg?display=1&htype=0&type=responsive-gallery"
      className="bodypart__image"
      alt=""
      key={curElem.id}
    />
  );
})}

注意:你原代码里的img标签属性写的是classname,正确拼写应为className,否则React不会识别为元素的类名;另外遍历渲染的元素需要添加唯一key属性,用photo的id作为值是最优选择。


内容的提问来源于stack exchange,提问作者Vivek Joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:39:02