You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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>
  );
}

关键修改说明

  1. 嵌套遍历:把statistics的map放到父数组的遍历循环内部,这样才能访问到每个locationData对象下的子数组。
  2. 可选链防护:用locationData.statistics?.map,如果某个地点没有statistics属性,会自动跳过而不报错,避免程序崩溃。
  3. 添加唯一key:给遍历生成的元素加上唯一key,符合React列表渲染规范,同时提升渲染性能。
  4. 补全类型定义:在locationData的类型里补上statistics的类型,让TypeScript提供正确的类型提示。

内容的提问来源于stack exchange,提问作者Lachy Schumacher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 20:42:23