import { deleteItem, getCartItems } from "../../services/cartService";
import { BsFillTrash2Fill } from "react-icons/bs";
import { MdOutlineRemoveShoppingCart } from "react-icons/md";
import swal from "sweetalert";
import { Link, useNavigate } from "react-router-dom";
import "./cart.css";

const Cart = ({ user }) => {
  const [item, setItem] = useState([]);
  let [totalAmount, setTotalAmount] = useState(0);
  const shopping = useRef(null);
  const navigate = useNavigate();
  const tot = useRef(null);

  const myCart = async () => {
    try {
      const res = await getCartItems().then((response) => {
        setItem(response.data[0].cartItems);
      });
    } catch (error) {
      console.log(error.response.data);
    }
  };

  //Delete item from cart

  const handleRemoveItem = (itemId) => {
    swal({
      title: "Remove from cart?",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    }).then(async (willDelete) => {
      if (willDelete) {
        const res = await deleteItem(itemId);
        myCart();
      }
    });
  };

  // Contunue Shopping

  const handleShopping = () => {
    navigate("/product");
  };

  const totalPrice = () => {
    item.map((it) => {
      setTotalAmount((totalAmount += it.product.price));
    });
    console.log(totalAmount);
  };

  useEffect(() => {
    myCart();
    totalPrice();
  }, []);

  if (!item) return null;

  console.log(item);

  if (user && item.length !== 0) {
    return (
      <>
        <div className="md:flex flex-row mt-24 text-2xl justify-evenly hidden">
          <div>Items</div>
          <div>Item Name</div>
          <div>Item Price</div>
          <div>Quantity</div>
          <div>Total Item Price</div>
          <div>Action</div>
        </div>
        {item.map((cartItem) => (
          <div
            className="flex flex-col w-full md:mt-0 mt-20"
            key={cartItem.product._id}
          >
            <div className="grid md:grid-cols-6 grid-cols-2 gap-4 md:gap-0 items-center text-center pt-2 pb-2 shadow-md shadow-black">
              <div className="h-56 grid place-items-center">
                <img
                  src={"http://" + cartItem.product.images?.host}
                  alt="image"
                  className="md:h-46 h-36 max-w-full"
                />
              </div>
              <div className="md:text-lg font-bold text-xl md:h-auto h:56 truncation">
                {cartItem.product.name}
              </div>
              <div className="text-4xl font-bold">
                ₹ {cartItem.product.price}
              </div>
              <div className="">
                <div className="text-3xl font-bold md:pe-16">
                  {cartItem.quantity}
                </div>
              </div>
              <div
                className="text-4xl font-bold"
                ref={tot}
                value={cartItem.product.price * cartItem.quantity}
              >
                {cartItem.product.price * cartItem.quantity}
              </div>
              <div className="text-4xl text-red-600 cursor-pointer ">
                <BsFillTrash2Fill
                  onClick={() => {
                    handleRemoveItem(cartItem._id);
                  }}
                />
                {/* {console.log(cartItem._id)} */}
              </div>
            </div>
          </div>
        ))}

        <div className="mt-5 grid grid-cols-6 w-full place-items-end gap-5">
          <div className="text-4xl font-bold col-span-4">Total Amount:</div>
          <div className="text-4xl font-bold w-full">{totalAmount}</div>
        </div>

        <div
          className="btn-shadow"
          ref={shopping}
          onMouseDown={(e) => {
            e.target.classList.add("btn-shadow-click");
          }}
          onMouseUp={(e) => {
            e.target.classList.remove("btn-shadow-click");
          }}
          onClick={handleShopping}
        >
          Continue Shopping
        </div>
        {/* <div onClick={totalPrice}>getToatl</div> */}
      </>
    );
  } else {
    return (
      <>
        <div className="flex flex-col md:min-h-[500px] min-h-screen justify-center items-center">
          <MdOutlineRemoveShoppingCart size={100} color="purple" />
          <h2 className="font-roboto">No Items Added to the Cart</h2>
          <Link to="/product">
            <button className="p-3 border border-solid border-purple-800 w-full text-center font-bold text-xl rounded-full duration-700 bg-purple-800 text-white cursor-pointer hover:bg-white hover:text-purple-800 no-underline">
              Start Shopping
            </button>
          </Link>
        </div>
      </>
    );
  }
};

export default Cart;

在useEffect中的这段代码中,‘myCart’函数首先返回一个空数组,然后返回响应的array.但我的"totalPrice"计算是在加载数组之前计算的.因此,它没有呈现所需的输出.如何停止获取空白数组或摆脱这种情况. 请帮帮忙.

推荐答案

totalAmount直接依赖于item,因此它不是(不应该是)自己的状态.

删除totalAmountsetTotalAmounttotalPrice,代之以

const totalAmount = item.reduce((sum, it) => {
  return sum + it.product.price;
}, 0);

现在totalAmount将永远是item中所有价格的总和.

另外,您永远不应该像声明totalAmount那样声明带有let的react 状态.totalAmount += it.product.price是一种危险的方法,在手动重新分配totalAmount时可能会导致意外行为.

Reactjs相关问答推荐

呈现组件元素(MAP)中的问题

FireBase Reaction Native-在呈现视图之前等待响应

如何使用useState响应快速/顺序状态更新

我如何在不被 destruct 的情况下将导航栏固定在顶部?

我在Route组件上使用元素属性,这样就不需要ID了吗?

.populate() 方法在 mongodb 中不起作用

MERN,将动态列表中的元素插入数组

console.logs 没有显示在浏览器控制台上,但显示在我的终端上

Yup.number().integer() 不将 1.0 视为小数,如何解决这个问题?

如何更改TimePicker中下拉菜单的背景 colored颜色 和字体 colored颜色 - MUI React

i18next中复数键的理解

如何在 React 过滤器中包含价格过滤器逻辑?

将水平滚动视图添加到底部导航选项卡

如何处理页面加载时发生的 reactjs 错误?

如何在 ChartJS 中操作 Y 轴

页面加载时不显示数组中的数据

在 Spring Cloud Gateway 中运行的 React SPA 页面刷新出现白标错误

如何在react 日历中自定义带有圆形边框的日期项?

react-admin useGetIdentity 只返回全名,id 未定义 头像未定义

我在使用 Elements of stripe 时使用 React router v6