调用TMDB API获取电影图片后map遍历返回undefined问题求助
问题:React中遍历图片数组返回undefined,直接访问元素却正常
我调用themoviedb的Fetch API获取电影图片列表,fetch获取后console.log显示数据正常:
getImages(movieId).then((imgs) => { setImages(imgs.backdrops); }).catch((err) => { console.error(err); });
但用map遍历images数组时返回undefined:
{ images.map((img) => { <Image source={img.file_path ? { uri: `https://image.tmdb.org/t/p/w500${img.file_path}` } : null} style={styles.movieImages} />; }) }
奇怪的是直接渲染第一张图片(images[0])却能正常显示:
<Image source={images[0].file_path ? { uri: `https://image.tmdb.org/t/p/w500${images[0].file_path}` } : null} style={styles.movieImages} />
怀疑是map写法有误,求问问题出在哪里?
问题原因与解决方法
问题出在**map的回调函数没有返回JSX元素**。当你在箭头函数里使用大括号{}时,必须显式写return来返回内容,否则回调默认返回undefined,遍历后得到的是全为undefined的数组,自然无法渲染。
修正方法有两种:
- 去掉大括号,利用箭头函数的隐式返回:
{ images.map((img) => <Image key={img.file_path} // React列表渲染必须添加唯一key属性 source={img.file_path ? { uri: `https://image.tmdb.org/t/p/w500${img.file_path}` } : null} style={styles.movieImages} /> ) }
- 在大括号内显式添加
return:
{ images.map((img) => { return <Image key={img.file_path} // React列表渲染必须添加唯一key属性 source={img.file_path ? { uri: `https://image.tmdb.org/t/p/w500${img.file_path}` } : null} style={styles.movieImages} />; }) }
另外补充:React列表渲染必须给每个元素添加唯一的key属性,这里用img.file_path作为key是合适的,因为它是图片的唯一路径。
而直接访问images[0]能正常工作,是因为你直接把对应的JSX元素传给了渲染逻辑,没有经过回调函数返回值的环节,所以不存在返回undefined的问题。
内容的提问来源于stack exchange,提问作者Brian Hansen
相关产品推荐
相关产品推荐

