reactjs React上下文未按预期工作:无法更新cartItems数组,并且addProductToCart函数不起作用

a14dhokn  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(122)

因此,当我在商店页面上单击“添加到购物车”时,它应该将商品添加到cartItem数组中,但没有发生任何事情,而且cartItems数组的类型似乎是“never[]”,我不知道如何在jsx中修复此问题。
Project link on GitHub
cart.context.jsx文件

import { useState, createContext } from "react";

export const addCartItem = (cartItems, productToAdd) => {
  const existingCartItem = cartItems.find(
    (cartItem) => cartItem.id === productToAdd.id
  );

  if (existingCartItem) {
    return cartItems.map((cartItem) =>
      cartItem.id === productToAdd.id
        ? { ...cartItem, quantity: cartItem.quantity + 1 }
        : cartItem
    );
  }

  return [...cartItems, { ...productToAdd, quantity: 1 }];
};

export const CartContext = createContext({
  cartItems: [],
  addItemToCart: () => {},
});

export const CartProvider = ({ children }) => {
  const [cartItems, setCartItems] = useState([]);

  const addItemToCart = (product) => {
    setCartItems(addCartItem(cartItems, product));
  };

  const value = { addItemToCart, cartItems };
  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
};

cart.jsx文件

import CartItem from "../components/cart-item";
import { toggleClass } from "./navigation";

import { useContext } from "react";
import { CartContext } from "../context/cart.context";

import "../scss/cart.scss";

const Cart = () => {
  const { cartItems } = useContext(CartContext);

  return (
    <div className={`card cart`} style={{ width: "18rem" }}>
      <button
        type="button"
        className="btn-close m-2"
        aria-label="Close"
        onClick={toggleClass}
      ></button>
      <div className="card-body text-center" style={{ height: "20rem" }}>
        <h5 className="card-title">Cart</h5>
        <div>
          {cartItems.length ? (
            cartItems.map((item) => <CartItem key={item.id} cartItem={item} />)
          ) : (
            <h5>The cart is empty</h5>
          )}
        </div>
        <button href="#" className="checkOutBtn mb-2 btn bg-dark text-white">
          Check Out
        </button>
      </div>
    </div>
  );
};

export default Cart;

购物车项目.jsx文件

const CartItem = ({ item }) => {
  const {name, imageUrl, price, quantity } = item;
  return  (
    <div className="card mb-3">
      <div className="row g-0">
        <div>
          <div className="col-md-4">
            <img
              src={imageUrl}
              className="img-fluid rounded-start"
              alt={name}
            />
          </div>
          <div className="col-md-8">
            <div className="card-body">
              <h5 className="card-title">{name}</h5>
              <p className="card-text">{price}</p>
              <p className="card-text">{quantity}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CartItem;

产品购物车.jsx文件

import { useContext } from "react";
import { CartContext } from "../context/cart.context";

const ProductCard = ({ product }) => {

  const { addItemToCart } = useContext(CartContext);
  const addProductToCart = () => addItemToCart(product);

  const { name, imageUrl, price } = product;

  return (
    <div className="col-md-3 my-2">
      <div className="card pb-3">
        <div
          className="image-container"
          style={{ height: "300px", overflow: "hidden" }}
        >
          <img src={imageUrl} className="card-img-top" alt={`${name}`} />
        </div>
        <div className="card-body d-flex justify-content-between">
          <p className="card-text d-inline">{name}</p>
          <span className="d-inline text-success">{price}$</span>
        </div>
        <button
          className="btn btn-success w-50 mx-auto"
          onClick={addProductToCart}
        >
          Add to cart
          <i className="fa fa-cart-plus mx-2" aria-hidden="true"></i>
        </button>
      </div>
    </div>
  );
};

我尝试从ProductCard调用addCartItem函数,它工作正常,并将项目添加到数组中,但数组没有更新,因此购物车组件没有呈现任何内容,因为数组为空。

fnx2tebb

fnx2tebb1#

NVM的家伙,我发现的问题,我没有设置提供者在index.js正确
我应该写什么

<BrowserRouter>
  <UserProvider>
    <ProductsProvider>
      <CartProvider>
        <App />
      </CartProvider>
    </ProductsProvider>
  </UserProvider>
</BrowserRouter>

我写的东西

<BrowserRouter>
  <UserProvider>
    <App />
  </UserProvider>
</BrowserRouter>

</React.StrictMode>

相关问题