绑定数据到MUI Select组件时出现map is not a function错误排查
MUI Select组件触发
map is not a function错误解析 相关代码与信息
数据类型定义
export type Airport = { iata: string, en: string } export type Airports = Airport[];
API调用方法
async function getAirports() { const { data, status } = await axios.get<Airports>('/Dictionary/GetAirports'); return data; } export const DictionaryService = { getAirports };
React状态与数据获取逻辑
const [stationList,setStationList] = React.useState<Airports>([]); useEffect(() => { const getData = async () => { try { const response = await DictionaryService.getAirports(); console.log(response); setStationList(response); } catch (err) { console.log(err); } }; getData(); }, []);
组件数据绑定代码
<Select inputProps={{ 'aria-label': 'Without label' }} onChange={handleChangeStation}> <MenuItem defaultChecked={true} value={'*'}><em>ALL</em></MenuItem> {stationList.map(({iata, en}) => { return ( <MenuItem key={iata} value={iata}> {en} </MenuItem> )})} </Select>
API响应结构
{ "airports": [ { "iata": "wqeq", "en": "asdasdad" }, { "iata": "qweqw", "en": "ssdasdasd" } ] }
问题根源
API返回的是一个包含airports数组的对象,但代码中直接将整个响应对象赋值给了stationList状态。而stationList被定义为数组类型(Airports即Airport[]),对象本身不存在map方法,因此调用stationList.map()时触发错误。同时,给axios.get指定的泛型Airports也不符合实际响应结构,存在类型不匹配问题。
修复方案
1. 修正API响应的类型定义
先定义匹配实际响应结构的类型:
export type AirportResponse = { airports: Airports; };
2. 修改API调用逻辑,提取数组
更新getAirports函数,从响应数据中提取airports数组返回:
async function getAirports() { const { data, status } = await axios.get<AirportResponse>('/Dictionary/GetAirports'); return data.airports; // 提取数组而非整个对象 }
或者,若不想修改API服务层,也可以在状态赋值时直接提取数组:
const response = await DictionaryService.getAirports(); setStationList(response.airports); // 取响应中的airports数组赋值给状态
经过上述修改后,stationList会成为正确的数组类型,调用map方法时就不会再触发错误。
内容的提问来源于stack exchange,提问作者user6408649
相关产品推荐
相关产品推荐

