【问题标题】:React JS - Add to cart featureReact JS - 添加到购物车功能
【发布时间】:2022-11-24 12:45:50
【问题描述】:

我正在构建一个用于学习 React 的小型电子商务平台。到目前为止,我已经构建了列表页面和购物车页面。在主列表页面中,我从一个 JSON 文件中获取数据,然后使用一个组件来呈现所有可用的项目。我映射 JSON 数据,然后为每个可用项目条目呈现相同的组件。 我在购物车页面中有一张桌子。每当按下添加到购物车按钮时,我必须将该项目的数据从该组件发送到购物车页面并在表中创建一个新条目。关于如何执行此操作的任何建议?

主屏幕

const DisplayData=JsonData.map(
        (info)=>{
            return(
                <Card name = {info.name} price = {info.price} image = {info.image}/>
            )
        }
    )

function Home() {
    let navigate = useNavigate(); 
    const routeChange = () =>{ 
    let path = `/Cart`; 
    navigate(path);
}
    return (
        /*Rendering the Home Screen*/
        <div className='home' style={{ backgroundImage: "url(/img/bg.jpg)"}}>
            <div className='topdiv'>
                <h1 className='logo'>Kemana Ecommerce</h1>
                <button className='cartbutton' onClick={routeChange}>View Cart</button>
            </div>
            <div className='container'>
                    {DisplayData}
            </div>
        </div>
      
    );
  }

卡片组件

const Card = (props)=>{
    return(
        /*Card Component*/
        <div className='card'>
            <img src={props.image}/>
            <h3>{props.name} - {props.price} Dollars</h3>
            <button>Add to Cart</button>
        </div>
    );
}

购物车页面

function Cart(){
    let navigate = useNavigate(); 
    const routeChange = () =>{ 
    let path = `/`; 
    navigate(path);
}
    return(
        <div className='Cart'>
            <button onClick={routeChange}>Back to Home</button><br/>
            <table>
                <tr>
                    <th>Item</th>
                    <th>Price</th>
                    <th>Quantity</th>
                </tr>
            </table>
        </div>
    );
}

【问题讨论】:

    标签: javascript reactjs json e-commerce shopping-cart


    【解决方案1】:

    方法 1:使用 JSON

    您提到购物车会自动显示来自 json 的数据,因此可能在单击卡片中的按钮时,您将一个项目附加到 json,该更改将反映在购物车中。唯一的问题是你要确保购物车会随着 json 的改变而改变。此外,在文件系统上使用 json 文件作为实时更改缓存在性能方面也不是很好。在 React 的会话中有许多更好的方法来存储信息

    方法二:React UseContext

    从某种意义上说,这可能有点矫枉过正,因为您可以通过使用相同的 useState 和 addItem 函数以类似但可扩展性较低的方式实现它,并将其放在购物车和卡片组件共享的父级中。但是,如果不查看整个项目,就无法可靠地识别该父组件。无论哪种方式,此提供程序都允许您在应用程序的任何位置访问“cartItems”变量,这甚至可以取代您从中获取购物车列表的 json 对象。请注意,cartItems 变量会在页面重新加载时重置,并且不会在会话之外持续存在。

    CartItemsProvider.jsx

    import React, { createContext, useContext, useState } from 'react'
    
    export const CartItemsContext = createContext({
        cartItems: [],
        setCartItems: () => null,
        addItem: () => null,
    })
    export const useCart = () => useContext(CartItemsContext)
    
    export const CartItemsProvider = ({ children }) => {
        const [cartItems, setCartItems] = useState([])
    
        const addItem = (newItem) => {
            setCartItems(prevItems => [...prevItems, newItem])
        }
    
        return (
            <CartItemsContext.Provider value={{ cartItems, setCartItems, addItem }}>
                {children}
            </CartItemsContext.Provider>
        )
    }
    

    应用程序的根目录(通常是“index.jsx”或“app.jsx”)

    import * as React from 'react';
    
    // 1. import `CartItemsProvider` component
    import { CartItemsProvider } from "insert file path here to './CartItemsProvider'";
    
    function App({ Component }) {
      // 2. Use at the root of your app
      return (
        <CartItemsProvider>
          <Component />
        </CartItemsProvider>
      );
    }
    

    卡片组件

    import { useCart } from "insert file path here to './CartItemsProvider'"
    const Card = (props)=>{
        const { addButton } = useCart();
        
        const handleClick = () => {
            addButton({
               // enter cart item info here
            })
        }
        return(
            /*Card Component*/
            <div className='card'>
                <img src={props.image}/>
                <h3>{props.name} - {props.price} Dollars</h3>
                <button onClick={handleClick}>Add to Cart</button>
            </div>
        );
    }
    

    主屏幕

    
    
    import { useCart } from "insert file path here to './CartItemsProvider'"
    function Home() {
      let navigate = useNavigate();
      const { cartItems } = useCart();
      const routeChange = () => {
        let path = `/Cart`;
        navigate(path);
      };
      return (
        /*Rendering the Home Screen*/
        <div className="home" style={{ backgroundImage: "url(/img/bg.jpg)" }}>
          <div className="topdiv">
            <h1 className="logo">Kemana Ecommerce</h1>
            <button className="cartbutton" onClick={routeChange}>
              View Cart
            </button>
          </div>
          <div className="container">
            {cartItems.map((info) => {
              return (
                <Card name={info.name} price={info.price} image={info.image} />
              );
            })}
          </div>
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多