简体   繁体   中英

React - Can .reduce() be updated like useState()?

I am working on a little project and I am currently working on the "Cart". The only part missing on the cart currently, is getting the total price of each product.

I've managed to do that, but if for instance you want 2 of a product. It does not update.

The products in the cart is inside of a context, and the price updates there whenever you increase, or decrease the amount of each product.

But the part where I display "total price" does not update. I have tried to use a useState() for this part, but with no success. I read a bit about useReducer() , but not really sure how it works. Is it exactly the same as JavaScript's .reduce() ?

Here is the part of the code where this needs to be calculated:

  // Add to cart context
  const { cartItems } = useContext(AddToCartContext);

  // Filtering double products
  let cart = cartItems.filter(
    (ele, ind) => ind === cartItems.findIndex((elem) => elem.id === ele.id && elem.size === ele.size)
  );

  // This adds all product prices together, displays a total price
  let totalPrice = cart.reduce(
    (totalPrice, item) => totalPrice + item.price,
    0
  )
  // Though, it does not update "live" like a useState.

Also, here is a picture of the object (how it looks like), might be useful: 在此处输入图像描述

Thanks!

Edit: Code for Context

AddToCartContext:

import React from "react";

const AddToCartContext = React.createContext([]);

export default AddToCartContext;

Code for AddToCartContext onClick:

<button
  type="button"
  onClick={() =>
    setCartItems((cartItems) => [
      ...cartItems,
      {
        name: props.name,
        price: props.price,
        color: props.mainImg?.colour,
        img: props.mainImg?.url,
        id: params.productid,
        size: selectedSize,
        count: 1,
      },
    ])
  }
  className={classes.add_to_cart}
>
  <Cart />
  add to cart
</button>

useReducer is the API provided by React to mimic the behaviour of Redux/Flux's pattern for updating state

view layer -> dispatch an action -> a reducer function to update your state based on your action

It is not related to the reduce of JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM