React中如何用TypeScript批量请求多个API获取图片并渲染到响应式瀑布流
报错根因
Cannot read property 'map' of undefined报错是因为useState未设置初始值,组件首次渲染时photosList为undefined,调用map方法直接触发异常。
完整解决方案
1. 定义TypeScript类型
先根据你的API实际返回结构定义数据类型,示例如下:
// 字段按照你的接口实际返回调整,这里假设每个接口返回单张图片信息 interface Photo { imgSrc: string; // 图片地址对应的接口字段,替换为你实际的字段名 alt?: string; // 可选的图片描述字段 width?: number; height?: number; }
2. 改写批量请求函数为TS版本
async function getPhotos(urls: string[]): Promise<Photo[]> { const promises = urls.map((url) => fetch(url).then((res) => res.json() as Promise<Photo>)); return Promise.all(promises); }
3. 修复组件逻辑
给useState设置空数组作为初始值,同时补全瀑布流渲染逻辑:
import { useState, useEffect } from 'react'; import ResponsiveMasonry, { Masonry } from 'react-responsive-masonry'; // 你的请求URL列表,替换为实际值 const API_URLS: string[] = ['接口地址1', '接口地址2']; // 瀑布流断点配置,可按照需求调整 const columnsCountBreakPoints = { 350: 1, 750: 2, 900: 3 }; function PhotoMasonry() { // 初始值设置为空数组,避免首次渲染map报错 const [photosList, setPhotosList] = useState<Photo[]>([]); // 可选的加载状态 const [loading, setLoading] = useState<boolean>(true); useEffect(() => { getPhotos(API_URLS) .then(data => { setPhotosList(data); }) .catch(err => { // 可自行补充错误处理逻辑 console.error('图片资源请求失败', err); }) .finally(() => { setLoading(false); }) }, []); if (loading) return <div>资源加载中...</div>; return ( <ResponsiveMasonry columnsCountBreakPoints={columnsCountBreakPoints}> <Masonry gutter={4}> {photosList.map((photo, index) => ( <img key={index} src={photo.imgSrc} alt={photo.alt || `图片${index}`} style={{ width: '100%', display: 'block' }} loading="lazy" // 可选,开启懒加载优化性能 /> ))} </Masonry> </ResponsiveMasonry> ) } export default PhotoMasonry;
内容的提问来源于stack exchange,提问作者Menna T-Allah Magdy
相关产品推荐
相关产品推荐

