如何从多层map函数调用中获取图标名称数组?
问题分析与解决思路
核心问题
你的代码存在两个关键问题导致图标无法渲染:
- 多层
map无返回值:所有map回调里都没有返回结果,最终icons是一个由undefined组成的数组,拼接后URL无效。 - 数据结构嵌套未处理:即使拿到图标,多层
map会生成嵌套数组,直接塞到img的src里会导致URL格式错误。
解决代码方案
根据你的需求,分两种场景处理:
场景1:只展示第一个天气图标
import { useSelector } from "react-redux"; export default function Icon() { // 加边界判断,避免数据未加载时报错 const icon = useSelector(state => { if (!state.api?.[0]?.city?.list?.[0]?.weather?.[0]) { return ''; } return state.api[0].city.list[0].weather[0].icon; }); return ( <div> {/* 只有当icon存在时才渲染图片 */} {icon && <img src={`https://openweathermap.org/img/wn/${icon}.png`} alt="天气图标" />} </div> ); }
场景2:展示所有天气图标
import { useSelector } from "react-redux"; export default function Icon() { // 用flatMap扁平化嵌套数组,提取所有图标 const icons = useSelector(state => { return state.api.flatMap(apiItem => apiItem.city.list.flatMap(listItem => listItem.weather.map(weatherItem => weatherItem.icon) ) ); }); return ( <div> {/* 遍历所有图标渲染 */} {icons.map((icon, idx) => ( <img key={idx} src={`https://openweathermap.org/img/wn/${icon}.png`} alt={`天气图标${idx+1}`} style={{ margin: '0 8px' }} /> ))} </div> ); }
原代码问题详解
- 你在
useSelector里的多层map都没有返回值(比如i.city.list.map(...)没有用return),所以每个map执行后返回的数组元素都是undefined,最终icons数组全是undefined,导致图片URL为https://openweathermap.org/img/wn/undefined.png,无法加载。 - 就算给每个
map加上return,得到的会是嵌套数组(如[[[icon1], [icon2]], ...]),直接转字符串后URL格式完全错误,无法匹配天气图标地址。
内容的提问来源于stack exchange,提问作者ydrea
相关产品推荐
相关产品推荐

