首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么setState()在我的情况下不起作用?

为什么setState()在我的情况下不起作用?
EN

Stack Overflow用户
提问于 2021-11-16 22:59:27
回答 1查看 75关注 0票数 0

我试图通过使用上下文来实现购物车。上下文运行良好,但我需要创建一个方法,每次单击删除一个产品。要做到这一点,我必须使用useState()函数。但是,它甚至不改变状态中的数据。

,这是我的函数代码。如果有什么不清楚的话请告诉我,

productsToPurchase 是一个数组,它拥有所有购买的产品,如下所示:

[{itemId: "ps-5", qty:2},{itemId: "iphone-xr", qty:4},{itemId:"ps-4", qty:7}]

代码语言:javascript
复制
export const CartContext = createContext()

class CartContextProvider extends Component {

    state = {
        productsToPurchase: [],
        totalPrice:[]
    }

    addProduct = (itemId, prices) => {
        this.setState(oldState => {
            const objWithIdExist = oldState.productsToPurchase.find((o) => o.itemId === itemId);
            return {
                productsToPurchase: !objWithIdExist
                    ? [...oldState.productsToPurchase, { itemId, qty: 1, price: prices }]
                    : oldState.productsToPurchase.map((o) =>
                        o.itemId !== itemId ? o : { ...o, qty: o.qty + 1 }
                    )
            }
        })

        this.setState(oldState=>{
            return{
                totalPrice: getTotalAmount(oldState.productsToPurchase)
            }
        })
    }

    decreaseProduct = (itemId) =>{

        this.setState(oldState=>{

            // catch the item by mapping
            return oldState.productsToPurchase.map(product=>{
                if (product.itemId === itemId){
                    if (product.qty === 1){
                        //remove the product from the list
                        console.log("qty is 1!")
                    }
                    else {
                        console.log("Quantity is more than 1")
                        return  {...product, qty: product.qty - 1}
                    }
                }
            })

        })

    }

    render() {
        return (
            <CartContext.Provider value={{...this.state, addProduct: this.addProduct, decreaseProduct: this.decreaseProduct}}>
                {this.props.children}
            </CartContext.Provider>
        )
    }
}

function getTotalAmount(productsToPurchase) {

    const totalPrice = []

    productsToPurchase.map((product, productIndex) =>{
        product.price.map((price, priceIndex)=>{
            if (productIndex === 0){
                totalPrice.push({currency: price.currency, amount: price.amount * product.qty})
            }
            else {
                totalPrice.map(total=>{
                    if (total.currency === price.currency){
                        total.amount = total.amount + (price.amount * product.qty)
                    }
                })
            }
        })
    })

    return totalPrice
}

export default CartContextProvider;
EN

回答 1

Stack Overflow用户

发布于 2021-11-16 23:32:45

如果您想从选定的产品数量中减去1,如果它达到0,则将其删除,请尝试如下

代码语言:javascript
复制
// Make sure you return the new state object in its entirety
this.setState(({ productsToPurchase, ...oldState }) => ({
  ...oldState,
  productsToPurchase: productsToPurchase.reduce((arr, product) => {
    // is this the selected product?
    if (product.itemId === itemId) {
      // product qty > 1, include it with decrement
      if (product.qty > 1) {
        return [...arr, {
          ...product,
          qty: product.qty - 1
        }]
      }
      return arr // otherwise exclude this product
    }
    // otherwise, just include this product
    return [...arr, product]
  }, [])
}))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69997048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档