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

React(Next.js)中遍历数据报错:TypeError: Cannot read property 'length' of undefined

解决React+Next.js中获取数据遍历时报错TypeError: Cannot read property 'length' of undefined

问题根源

  • 初始状态未正确初始化:useState<any>() 的初始值是undefined,组件首次渲染时直接访问data.length会触发报错。
  • 接口数据结构处理错误:https://dummyjson.com/products 返回的是包含products数组的对象,而非直接数组,你把整个响应对象赋值给data,导致data本身没有length属性。
  • map遍历逻辑错误:map(({}) => ...) 未正确接收遍历项,且key和title错误地使用外层data而非当前遍历项。

修复后的代码

import { useEffect, useState } from "react"

export default function Test() {
  // 初始化为空数组,避免首次渲染时undefined报错
  const [products, setProducts] = useState<any[]>([]);

  useEffect(() => {
    const callData = async () => {
      // 解构获取接口返回的products数组
      const { products } = await fetch('https://dummyjson.com/products').then(res => res.json())
      setProducts(products)
    }
    callData()
  }, [])

  return(
    <div>
      {
        products.length > 0 
          ? products.map((item) => <p key={item.id}>{item.title}</p>) 
          : <h3>暂无数据</h3>
      }
    </div>
  )
}

额外优化建议

  • 类型规范:避免使用any,可以定义类型约束数据结构:
    type Product = {
      id: number;
      title: string;
      // 根据需求添加其他字段
    }
    // 替换为 useState<Product[]>([])
    
  • 错误捕获:给请求添加异常处理,避免请求失败导致的页面异常:
    const callData = async () => {
      try {
        const { products } = await fetch('https://dummyjson.com/products').then(res => res.json())
        setProducts(products)
      } catch (err) {
        console.error('数据请求失败:', err)
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:26:14