Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

reactjs - React, context remove item from cart

I have a demo here

Its a simple cart app where I'm listing products and then adding them to a cart components

It uses context for the app state.

I'd now like to be able to remove items from the cart but I'm struggling to get this to work.

Do I need to add a DeleteCartContext.Provider

import React, { useContext } from "react";
import { CartContext } from "./context";
import { IProduct } from "./interface";

const Cart = () => {
  const items = useContext(CartContext);

  const handleClick = (
    e: React.MouseEvent<HTMLInputElement, MouseEvent>,
    item: IProduct
  ) => {
    e.preventDefault();
  };

  const cartItems = items.map((item, index) => (
    <div>
      <span key={index}>{`${item.name}: £${item.price}`}</span>
      <input type="button" value="-" onClick={e => handleClick(e, item)} />
    </div>
  ));

  return (
    <div>
      <h2>Cart</h2>
      {cartItems}
    </div>
  );
};

export default Cart;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are many ways to control Items in Context so I tried to answer as similar to your structure, here is how you do that:

import React, { useContext } from "react";
import { CartContext, RemoveCartContext } from "./context";
import { IProduct } from "./interface";

const Cart = () => {
  const items = useContext(CartContext);
  const removeItem = useContext(RemoveCartContext);

  const handleClick = (
    e: React.MouseEvent<HTMLInputElement, MouseEvent>,
    item: IProduct
  ) => {
    e.preventDefault();
  };

  const cartItems = items.map((item, index) => (
    <div>
      <span key={index}>{`${item.name}: £${item.price}`}</span>
      <input type="button" value="+" onClick={e => handleClick(e, item)} />
      <input type="button" value="-" onClick={e => removeItem(item)} />
    </div>
  ));

  return (
    <div>
      <h2>Cart</h2>
      {cartItems}
    </div>
  );
};

export default Cart;
import React, { createContext, useCallback, useRef, useState } from "react";

export const CartContext = createContext([]);
export const AddCartContext = createContext(item => {});
export const RemoveCartContext = createContext(item => {});

export const CartProvider = ({ children }) => {
  const [items, setItems] = useState([]);
  const itemsRef = useRef(items);
  itemsRef.current = items;

  return (
    <AddCartContext.Provider
      value={useCallback(item => {
        setItems([...itemsRef.current, item]);
      }, [])}
    >
      <RemoveCartContext.Provider
        value={useCallback(item => {
          const newItems = itemsRef.current.filter(
            _item => _item.id !== item.id
          );
          setItems(newItems);
        }, [])}
      >
        <CartContext.Provider value={items}>{children}</CartContext.Provider>
      </RemoveCartContext.Provider>
    </AddCartContext.Provider>
  );
};

and here is a working demo: https://stackblitz.com/edit/react-ts-cart-context-mt-ytfwfv?file=context.tsx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...