You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何将商品数组传递至Cart组件并展示?

How to Share Cart Items Between ProductCard and Cart Components in React

Hey there! The problem you're running into is super common in React—when two components need to share data, you need to lift the shared state up to their closest common parent component. Right now, your cart items are stored inside ProductCard, which means Cart can't access that data. Let's fix this step by step:

Step 1: Move Cart State to a Common Parent

First, let's move the cart state and add-to-cart logic out of ProductCard and into a parent component (like your App.js). This way, both components can access and update the cart data.

Here's what the parent component might look like:

import { useState } from 'react';
import ProductCard from './ProductCard';
import Cart from './Cart';

// Replace with your actual product data
const sampleProduct = {
  name: "Wireless Headphones",
  price: 79.99,
  quantity: 10,
  image: "headphones.jpg"
};

function App() {
  // Shared cart state lives here now
  const [cartItems, setCartItems] = useState([]);

  // Function to add items to cart, passed down to ProductCard
  const addToCart = (product) => {
    // Use previous state to ensure we're updating from the latest version
    setCartItems(prevItems => [...prevItems, { name: product.name, price: product.price }]);
  };

  return (
    <div style={{ display: "flex", gap: "2rem", padding: "2rem" }}>
      {/* Pass the addToCart function to ProductCard */}
      <ProductCard product={sampleProduct} addToCart={addToCart} />
      {/* Pass cart items to Cart for display */}
      <Cart items={cartItems} />
    </div>
  );
}

export default App;

Step 2: Update ProductCard to Use Parent's addToCart

Remove the local items state from ProductCard and instead use the addToCart function passed via props:

import { Card, Button } from 'react-bootstrap';

function ProductCard(props){
  const addToCart = () =>{
    // Call the parent's addToCart function with the current product
    props.addToCart(props.product);
  };

  return(
    <div>
      <Card className="card-style" border="primary" style={{width:'18rem', flex: 1}}>
        <Card.Img variant="top" src={props.product.image} />
        <Card.Body>
          <Card.Title>{props.product.name}</Card.Title>
          <Card.Text>Price: ${props.product.price}, Quantity: {props.product.quantity} </Card.Text>
          <Button onClick={addToCart}>Add to Cart</Button>
        </Card.Body>
      </Card>
    </div>
  )
}
export default ProductCard

Step 3: Update Cart to Display the Items

Modify the Cart component to accept the items prop and render them in the table:

import { Table } from 'react-bootstrap';

function Cart({ items }){
  return(
    <div>
      <Table striped border hover>
        <thead>
          <tr>
            <th>Products</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>
          {/* Map over items to render each cart entry */}
          {items.map((item, index) => (
            <tr key={index}>
              <td>{item.name}</td>
              <td>${item.price}</td>
            </tr>
          ))}
        </tbody>
      </Table>
    </div>
  )
}
export default Cart;

Quick Notes:

  • Why lift state? React uses one-way data flow—child components can't directly access sibling component state. Moving shared state to a parent lets both components interact with it.
  • Functional state updates: Using prevItems ensures we always update from the latest state, avoiding bugs from stale closures.
  • Key prop: We used index here for simplicity, but if your products have unique IDs (like product.id), use that instead—it’s more reliable for React’s rendering optimizations.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:33:25