反应状态和购物车的问题

Trouble with react state and shopping cart

我已经为购物车定义了一些反应上下文,我希望能够在每个子组件中访问它。我还定义了一些方法(添加到购物车和从购物车中删除)。我无法使用 addToCart 功能:

import React, { useContext, useState } from "react";

const ShoppingCartContext = React.createContext();

export function useShoppingCart() {
    return useContext(ShoppingCartContext);
}

export function ShoppingCartProvider({ children }) {
    const [shoppingCart, setShoppingCart] = useState([]);

    function addToCart(item) {
        setShoppingCart(shoppingCart.concat(item));
    }

    function removeFromCart(item) {
        const index = shoppingCart.indexOf(item);
        setShoppingCart(shoppingCart.splice(index, 1));
    }

    const value = { shoppingCart, setShoppingCart, addToCart, removeFromCart };

    return (
        <ShoppingCartContext.Provider value={value}>
            {children}
        </ShoppingCartContext.Provider>
    );
}

在我想访问购物车的文件中,我是这样做的:

const { shoppingCart, setShoppingCart, addToCart, removeFromCart } = useShoppingCart();

然后,在 useEffect() 中,我这样做:

addToCart(["item"])
console.log(shoppingCart)

但它 console.logs 是一个空数组:

因此,假设 useEffect 在您的子组件初始渲染后调用,会发生以下情况

addToCart(["item"])  // context state is [], a rerender with the new state is scheduled
console.log(shoppingCart) // context state is [], an empty array is logged

在此之后,状态更新并且您的子组件重新呈现。如果将 console.log 移到组件主体,您将看到变化


const MyShoppingCartConsumingComponent = () => {
  const { shoppingCart, setShoppingCart, addToCart, removeFromCart } = useShoppingCart();
  
  React.useEffect(() => {
     addToCart(['item'])
  }, [])

  console.log(shoppingCart)

  return <p>yo!</p>
}

将记录类似的内容


[]
['item']