You need to enable JavaScript to run this app. Material-ui Drawer组件不渲染handleAddToCart添加的内部商品项
优惠活动
大模型
产品
解决方案
定价
更多

Material-ui Drawer组件不渲染handleAddToCart添加的内部商品项

问题根因&修复方案

1. 最核心的渲染失败原因:map 回调没有返回JSX元素

你在Cart组件中写的cart.map使用大括号包裹函数体,但没有写return语句,导致遍历返回的全是undefined,自然不会渲染任何商品内容。

2. 附加错误点

  • 标题重复渲染:你将购物车标题放在了map循环内,会随商品数量重复生成多次,应该移到循环外
  • 缺少唯一key:遍历生成的JSX元素需要添加唯一key属性,避免React告警
  • 崩溃报错原因:你直接将对象/数组类型的变量作为文本渲染,大概率是product.productPictures为数组类型,不能直接赋值给img的src属性,需要取数组内的图片地址字符串;另外初始状态中products被定义为对象{},但你在HomePage中用products.length判断长度,对象无length属性,建议初始值改为空数组[]

修复后的Cart组件代码

import { StyledButton } from './styles'
import Badge from '@material-ui/core/Badge'
import Drawer from '@material-ui/core/Drawer'
import AddShoppingCartIcon from '@material-ui/icons/AddShoppingCart'
import { useState } from 'react'
import { useSelector } from 'react-redux'
import { ProductPicture } from '../ProductPicture'

export const Cart = function() {
  const { cart } = useSelector(({productReducer}) => ({
    cart: productReducer.cart,
  }))
  const [openCart, setOpenCart] = useState(false)
  return(
    <>
      <StyledButton onClick={() => setOpenCart(true)}>
        <Badge color='error' badgeContent={cart.length}>
          <AddShoppingCartIcon />
        </Badge>
      </StyledButton>
      <Drawer
        anchor='right'
        open={openCart}
        onClose={() => setOpenCart(false)}
      >
        <h3>Productos en tu carrito</h3>
        {!!cart && cart.length > 0 && cart.map(product => (
          // 用小括号替代大括号实现隐式返回,也可保留大括号加return语句
          <section key={product._id}>
            {/* 如果productPictures是数组,取第一个元素即可:product.productPictures[0] */}
            <img src={product.productPictures} alt={product.name} /> 
            <p>price: {product.price}</p> 
            <p>prodname: {product.name}</p>
          </section>
        ))}
      </Drawer>
    </>
  )
}

Reducer初始值优化

把productReducer的初始状态中products改为空数组,避免长度判断报错:

const initialSate = {
  products: [], // 原初始值为{},改为数组匹配接口返回结构
  cart: [],
  amount: 0,
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 05:06:01