使用React Hooks开发播客主profile组件时报错"Map is not a function"
问题根因
.map 是仅数组原型上存在的方法,报错说明执行 podcasts.map 时,podcasts 不是数组类型:
- 你虽然给
podcasts初始化了空数组,但getPodcast(id)接口返回的结果不符合预期,比如返回了null、undefined、或者包裹了列表的外层对象(比如{ code:200, data: [], msg: '' }这类结构),直接执行setPodcasts(podcasts)就会覆盖初始的空数组,导致后续调用map失败。 - 另外你代码中的映射逻辑写法也有问题:
podcast.name({...})属于把podcast.name当做函数调用,如果你的需求是给播客项新增edit字段,应该直接返回新对象,而不是调用podcast.name方法。
解决方案
- 修正接口数据处理逻辑
拿到接口返回值后先做格式校验,确保写入state的永远是数组:
useEffect(() => { ;(async function () { const categories = await getCategories() const podcastRes = await getPodcast(id) // 校验播客返回值是否为数组,不是的话兜底为空数组;如果接口返回的是包了一层的结构,自行取对应字段比如 podcastRes.data const finalPodcasts = Array.isArray(podcastRes) ? podcastRes : [] setCategories(categories) setPodcasts(finalPodcasts) setIsLoading(false) })() }, [id])
- 修正列表映射逻辑,渲染时加兜底
渲染ResponsiveList的data属性时,先做数组校验,同时修正映射写法:
<ResponsiveList data={Array.isArray(podcasts) ? podcasts.map((podcast: any) => ({ ...podcast, edit: ( <Button variant="contained" color="primary" fullWidth onClick={() => handleEditPodcast(podcast)} > Edit </Button> ), })) : []} // 其余属性保持不变 keys={[ { key: 'podcasts', label: 'Podcast Name' }, { key: 'categories', label: 'Podcast Categories' }, { key: 'description', label: 'Podcast Niche' }, { key: 'Reach', label: 'Podcast Reach' }, { key: 'edit', label: 'Edit', }, ]} emptyMessage="It seems that you have not created a podcast yet, go out and start one 😢" />
如果需要更稳妥的防护,可以在isLoading为true时渲染加载状态,避免接口返回前不必要的渲染:
if (isLoading) return <div>加载中...</div> // 再返回ResponsiveList组件
内容的提问来源于stack exchange,提问作者BillyWalsh
相关产品推荐
相关产品推荐

