React遍历products报Objects are not valid as a React child错误
报错根因
报错信息提示found: object with keys {rate, count},直接对应代码中直接渲染product.rating的逻辑:fakestoreapi返回的产品数据中,rating字段是包含rate(评分值)、count(评论数)两个属性的对象,React不支持直接渲染普通对象作为文本节点。
除此之外代码还有两处逻辑错误:
- 产品列表传参多嵌套一层数组:接口返回的
response.data本身就是包含20个产品对象的数组,调用渲染函数时写render_products([itemData]),相当于把整个产品数组包裹成新数组的第一个元素,导致入参结构不符合预期,你之前打印日志看到入参只有一个对象,就是被嵌套后的完整产品数组。 - 字段名和接口返回结构不匹配:接口返回的产品字段没有
item_name、current_price、href,对应字段为title(产品名称)、price(价格)、image(产品图片地址),即使解决对象渲染报错,这些字段也会显示为undefined。
修复步骤
- 修正渲染函数传参,去掉多余的数组包裹:
// 原错误代码 {render_products([itemData])} // 修正后 {render_products(itemData)}
- 调整渲染函数逻辑:直接遍历传入的产品数组,不要取
Products[0];拆分rating对象渲染具体数值;替换为接口返回的正确字段名;给列表项补充唯一key属性避免渲染警告。修正后的渲染函数代码如下:
const render_products = (Products) => { return <div className='category-section fixed'> <h2 className="text-3xl font-extrabold tracking-tight text-gray-600 category-title">Products</h2> <div className="m-6 p-3 mt-10 ml-0 grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-6 xl:gap-x-10" style={{ maxHeight: '800px', overflowY: 'scroll' }}> {Products.map(product => ( <div className="group relative shadow-lg" key={product.id}> <div className=" min-h-80 bg-gray-200 aspect-w-1 aspect-h-1 rounded-md overflow-hidden group-hover:opacity-75 lg:h-60 lg:aspect-none"> <img alt="Product Image" src={product.image} className="w-full h-full object-center object-cover lg:w-full lg:h-full" /> </div> <div className="flex justify-between p-3"> <div> <h3 className="text-sm text-gray-700"> <a href="#"> <span aria-hidden="true" className="absolute inset-0" /> <span style={{ fontSize: '16px', fontWeight: '600' }}>{product.title}</span> </a> <p>Tag -</p> </h3> <p className="mt-1 text-sm text-gray-500">Rating: {product.rating.rate} ({product.rating.count}条评价)</p> </div> <p className="text-sm font-medium text-green-600">${product.price}</p> </div> </div> ))} </div> </div> }
- 清理渲染函数中多余的调试console代码即可正常运行。
内容的提问来源于stack exchange,提问作者Sithija Piyuman Thewa Hettige
相关产品推荐
相关产品推荐

