如何在React(Next.js)中使用data.map函数处理接口数据
在React+Next.js中用map处理接口返回的数据
先直接给你修正代码并解释关键点,你的代码里有个核心问题:调用https://dummyjson.com/products返回的是包含products数组的对象,你直接把整个响应存进state了,这样没法直接用map,得先提取数组部分。
完整可运行代码
import { useEffect, useState } from "react" // 定义产品类型,代替any,提升代码健壮性 interface Product { id: number; title: string; price: number; description: string; category: string; image: string; } export default function Test() { // 初始化state为空数组,明确类型为Product数组 const [products, setProducts] = useState<Product[]>([]); useEffect(() => { const fetchProducts = async () => { try { const res = await fetch('https://dummyjson.com/products'); const data = await res.json(); // 提取接口返回的products数组存入state setProducts(data.products); } catch (err) { console.error('数据请求失败:', err); } }; fetchProducts(); }, []); return ( <div style={{ padding: '2rem' }}> <h2>产品列表</h2> {/* 数据未加载完成时显示提示 */} {products.length === 0 && <p>加载中...</p>} {/* 数据加载完成后用map渲染 */} {products.length > 0 && ( <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '1.5rem' }}> {products.map(product => ( // 必须给每个元素加唯一key,用id最稳妥 <div key={product.id} style={{ border: '1px solid #e5e7eb', borderRadius: '8px', padding: '1rem' }}> <img src={product.image} alt={product.title} style={{ width: '100%', height: '200px', objectFit: 'contain', marginBottom: '1rem' }} /> <h3 style={{ fontSize: '1.25rem', margin: '0 0 0.5rem' }}>{product.title}</h3> <p style={{ color: '#ef4444', fontWeight: 'bold', margin: '0 0 0.5rem' }}>${product.price}</p> <p style={{ fontSize: '0.875rem', color: '#6b7280', margin: '0 0 0.5rem' }}>{product.description}</p> <p style={{ fontSize: '0.75rem', color: '#9ca3af' }}>分类:{product.category}</p> </div> ))} </div> )} </div> ); }
核心要点说明
- 提取正确的数据:接口返回的结构是
{ products: [...], total: ..., skip: ..., limit: ... },必须把data.products赋值给state,不然state里不是数组,没法用map - 类型定义:用
interface Product代替any,能获得编辑器的类型提示,避免写错字段 - 条件渲染:判断
products.length来处理加载状态,防止数据没回来时调用map导致报错 - key的必要性:map渲染的每个元素必须有唯一key,这里用产品的
id(唯一标识),不要用数组索引作为key,避免渲染异常 - 错误处理:给fetch加try/catch,捕获请求失败的情况,方便排查问题
内容的提问来源于stack exchange,提问作者Jennie
相关产品推荐
相关产品推荐

