使用SWR+NextJS处理嵌套对象与数组时的map报错问题
问题解决:无法渲染嵌套数组数据(TypeError: Cannot read properties of undefined (reading 'map'))
错误原因
你出错的核心是对数据结构的理解偏差:data.location是一个数组,不是单个对象。你能通过data.location.map()遍历数组里的每个地点对象,但statistics子数组属于数组里的单个地点元素,而非data.location这个数组本身的属性。直接写data.location.statistics必然得到undefined,调用map自然会抛出错误。
修正后的代码
"use client"; import React from 'react'; import useSWR from 'swr'; export default function Home() { const resource = "https://api.npoint.io/1a3c1760fd86a94b1ff5" const fetcher = (url: RequestInfo | URL) => fetch(url).then((res) => res.json()); const { data, error, isLoading } = useSWR(resource, fetcher) if (error) return <div>failed to load</div> if (isLoading) return <div>loading...</div> return ( <div> {data.location.map((locationData: { id: string; location: string; manager: string; statistics: { type: string; rank: string; }[] }) => { return ( <div key={locationData.id}> <p>{locationData.id}</p> <p>{locationData.location}</p> <p>{locationData.manager}</p> {/* 遍历当前地点的statistics子数组 */} <div> {locationData.statistics?.map((stat) => ( <div key={`${locationData.id}-${stat.type}`}> <p>{stat.type}</p> <p>{stat.rank}</p> </div> ))} </div> </div> ) })} </div> ); }
关键修改说明
- 嵌套遍历:把
statistics的map放到父数组的遍历循环内部,这样才能访问到每个locationData对象下的子数组。 - 可选链防护:用
locationData.statistics?.map,如果某个地点没有statistics属性,会自动跳过而不报错,避免程序崩溃。 - 添加唯一key:给遍历生成的元素加上唯一
key,符合React列表渲染规范,同时提升渲染性能。 - 补全类型定义:在
locationData的类型里补上statistics的类型,让TypeScript提供正确的类型提示。
内容的提问来源于stack exchange,提问作者Lachy Schumacher
相关产品推荐
相关产品推荐

