子组件对API返回的shiftDetails执行map报undefined is not a function错误
问题原因
1. 核心报错原因
你调用shift/{id}接口返回的shiftDetails是单个对象类型,而map()是JavaScript数组的专属方法,对非数组类型调用map()就会抛出undefined is not a function错误。
2. 其他隐藏问题
- 即便你误将
shiftDetails转为数组,你在map回调中取值用的是shiftDetails.shift_name,而不是遍历项item.shift_name,也会拿到错误值 useCallback的依赖数组遗漏了id参数,当传入的id发生变化时,不会重新触发详情接口请求,会一直展示旧数据- 没有做加载态判断,接口返回前
shiftDetails为空时直接取值也可能触发报错
修复方案
第一步:修正接口请求的依赖逻辑
给useCallback补全id依赖:
const id = props.id; const getShiftDetails = useCallback(() => { Apicall('shift/' + id) .then(async (resp) => { if (resp) { setShiftDetails(resp.data); } else { Alert.alert('Error', resp); } }) .catch((err: any) => { console.log(err); }); }, [id]); // 新增id作为依赖,id变化时自动重新获取详情 useEffect(() => { getShiftDetails(); }, [getShiftDetails]);
第二步:修正渲染逻辑,删除错误的map调用
因为单个id对应一条班次详情,直接从shiftDetails对象取值即可,不需要遍历:
<View> {/* 先判断shiftDetails存在再渲染,避免加载阶段报错 */} {shiftDetails ? ( <> <Text> {shiftDetails.shift_name} </Text> <Text> {StartTime} </Text> <Text> {EndTime} </Text> </> ) : <Text>加载中...</Text>} </View>
如果你的业务逻辑是shift/{id}接口需要返回数组类型,先确认后端接口返回格式是否符合预期,再将shiftDetails的初始值设为空数组[]即可。
内容的提问来源于stack exchange,提问作者pratteek shaurya
相关产品推荐
相关产品推荐

