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

React遍历API响应对象获取图片regular url的报错解决

解决React中遍历API响应数组报错的问题

错误原因

你当前把API返回的完整响应对象存入了searchImages state,但这个对象本身不是数组,而是包含results数组的顶层对象。数组的map方法只能在数组上调用,所以直接对searchImages调用map会抛出undefined is not a function错误。

修复步骤

1. 正确存储API返回的数组

在fetch的回调中,不要直接存整个响应对象,而是提取其中的results数组存入state:

const [searchImages, setSearchImages] = useState([]);
    
useEffect(() => {
    fetch(`https://api.unsplash.com/search/photos/?client_id=btWDn-ckRUbNxJA&count=2&query=${searchInput}&per_page=2&orientation=landscape`)
    .then(response => response.json())
    .then(images => {
        // 提取results数组存入state,同时做兜底处理
        setSearchImages(images.results || []);
    })
    .catch(err => console.error('请求失败:', err)); // 增加错误捕获逻辑
}, [searchInput]) // 依赖项添加searchInput,确保搜索词变化时重新发起请求

注:images.results || []是为了防止API响应中无results字段时,state不会变为undefined,避免后续map调用报错。

2. 安全遍历数组

渲染时使用可选链操作符?.,进一步避免数组未初始化或为空时的报错:

{searchImages?.map(item => (
    <img className='image-item' key={item.id} src={item.urls.regular} alt='cool' />
))}

额外优化建议

  • 确保searchInput在组件中已正确定义,否则请求URL中的${searchInput}会导致无效请求。
  • 添加加载状态提示,提升用户体验:
const [isLoading, setIsLoading] = useState(false);

useEffect(() => {
    setIsLoading(true);
    fetch(`https://api.unsplash.com/search/photos/?client_id=btWDn-ckRUbNxJA&count=2&query=${searchInput}&per_page=2&orientation=landscape`)
    .then(response => response.json())
    .then(images => {
        setSearchImages(images.results || []);
        setIsLoading(false);
    })
    .catch(err => {
        console.error('请求失败:', err);
        setIsLoading(false);
    });
}, [searchInput])

// 渲染逻辑
{isLoading ? <div>加载中...</div> : (
    searchImages?.map(item => (
        <img className='image-item' key={item.id} src={item.urls.regular} alt='cool' />
    ))
)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:27:16