React Router v6中Product.js的data.map报错:不是函数求助
问题分析与解决
核心原因
你调用的fakestoreapi单品接口(比如https://fakestoreapi.com/products/{id})返回的是单个商品对象,不是数组。而map是数组专属方法,直接对单个对象调用map必然触发data.map is not a function错误——和data.x.map无关,因为接口返回结构里根本没有可遍历的数组。
解决方案
1. 调整Product.js的数据处理逻辑
既然返回的是单个对象,不需要用map,直接读取对象属性渲染即可。示例代码如下:
import { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; function Product() { const { id } = useParams(); const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch(`https://fakestoreapi.com/products/${id}`) .then(res => res.json()) .then(result => { setData(result); setLoading(false); }) .catch(err => { setError(err); setLoading(false); }); }, [id]); if (loading) return <div>加载中...</div>; if (error) return <div>加载失败:{error.message}</div>; if (!data) return <div>无商品数据</div>; // 直接渲染单个商品属性,无需map return ( <div className="product-detail"> <img src={data.image} alt={data.title} width="200" /> <h2>{data.title}</h2> <p>价格:${data.price}</p> <p>描述:{data.description}</p> <p>分类:{data.category}</p> </div> ); } export default Product;
2. 确认路由配置正确性
确保在路由中正确传递商品ID参数:
- 在FeaturedProduct.js的商品项中,跳转链接应为:
<Link to={`/product/${product.id}`}>查看详情</Link>
- 根路由配置示例:
import { Routes, Route } from "react-router-dom"; import FeaturedProduct from "./FeaturedProduct"; import Product from "./Product"; function App() { return ( <Routes> <Route path="/" element={<FeaturedProduct />} /> <Route path="/product/:id" element={<Product />} /> </Routes> ); }
额外提示
- 调用API前务必确认返回格式:列表接口(
https://fakestoreapi.com/products)返回数组,单品接口返回单个对象,两者处理逻辑完全不同。 - 必须处理加载、错误、空数据状态,避免页面因数据异常崩溃。
内容的提问来源于stack exchange,提问作者jack601
相关产品推荐
相关产品推荐

