使用数组数据中的键识别每个项目以添加购物车按钮。反应。终极版

Identify each item using keys from array data for add cart button. Reactjs. Redux

我展示了产品名称、价格和按钮(添加到购物车)。

问题是我的产品数组(商店组件)中的第一个数据(连帽衫白色)是唯一加起来的数据。在使用我的处理程序进行调度时,我找不到识别每个产品数组的方法。

Array products sample

const data = {
    products:[
        {   
            id: 1,
            name: 'Hoodie white',
            price: 19.99,

        },
        {
            id: 2,
            name: 'Hoodie black',
            price: 19.99,
        }
    ],

    cart: [],
    total: 0,
}

const ProductComponent=()=>{

    const products= useSelector(state=>state.products);
    const dispatch = useDispatch(0);
    const [productid] = useState(0)
    const purchaseHandler=(e)=>{ 
        dispatch({ type: "PURCHASE", payLoad: products[productid] });
    }
    return(
             products.map((product, i)=>{
            return(
            <>
            <img src={products.image} className="product-image" alt={product.name} />
            <div className='namebtn'>
            <h3 className='product-name-text' key={i}>{product.name}</h3>
            <div key={i}>${product.price}</div>
            <button onClick={purchaseHandler} className="addToCart">Add to Cart</button>
            </div>
            </>
        )})    
    )
    }

为什么不将 product.id 传递给 purchaseHandler 函数

const ProductComponent = () => {
  const products = useSelector((state) => state.products);
  const dispatch = useDispatch(0);
  const purchaseHandler = (e, productid) => {
    dispatch({ type: 'PURCHASE', payLoad: products[productid] });
  };
  return products.map((product, i) => {
    return (
      <>
        <img src={products.image} className="product-image" alt={product.name} />
        <div className="namebtn">
          <h3 className="product-name-text" key={i}>
            {product.name}
          </h3>
          <div key={i}>${product.price}</div>
          <button onClick={(e) => purchaseHandler(e, product.id)} className="addToCart">
            Add to Cart
          </button>
        </div>
      </>
    );
  });
};