值更改时强制重新挂载

yyyllmsg  于 2022-10-15  发布在  React
关注(0)|答案(1)|浏览(162)

我有一些文件,为我的商店网站在下拉列表中建立一个购物车。
一个文件将所选项目添加到将成为我的购物车的数组中。另一个文件是CartDropdown组件本身。我的购物车只在我关闭和打开它(重新挂载)时显示物品,但我希望每次添加新物品时它都重新挂载。
新增项目功能:

const ProductContainer = ({ productInfo }) => {
  const { cartProducts, setCartProducts } = useContext(CartContext);
  const cartArray = cartProducts;

  const addProduct = () => {
    productInfo.quantity = 1;
    if (cartArray.includes(productInfo)) {
      const index = cartArray.findIndex((object) => {
        return object === productInfo;
      });
      cartProducts[index].quantity++;
      setCartProducts(cartArray);
    } else {
      cartArray.push(productInfo);
      setCartProducts(cartArray);
    }
    // setCartProducts(cartArray)
    console.log(cartProducts);
    // console.log(cartArray)
  };
};

下拉式组件

const CartDropdown = () => {
  const { setCartProducts, cartProducts } = useContext(CartContext);
  const { setProducts, currentProducts } = useContext(ProductsContext);
  // useEffect(() => {}, [cartProducts])
  const cleanCart = () => {
    const cleanProducts = currentProducts;
    console.log(cleanProducts);
    for (let i in cleanProducts) {
      if (cleanProducts[i].hasOwnProperty("quantity")) {
        cleanProducts[i].quantity = 0;
      }
    }
    setProducts(cleanProducts);
    setCartProducts([]);
  };
  return (
    <div className="cart-dropdown-container">
      <div className="cart-items">
        {cartProducts.map((product) => (
          <div key={product.id}>
            <img src={product.imageUrl}></img>
          </div>
        ))}
      </div>
      <button onClick={cleanCart}>CLEAN CART</button>
      <Button children={"FINALIZE PURCHASE"} />
    </div>
  );
};

如何在每次cartProducts更改时强制重新挂载下拉菜单?
购物车上下文:

export const CartContext = createContext({
    isCartOpen: false,
    setIsCartOpen: () => { },
    cartProducts: [],
    setCartProducts: () => { }
})

export const CartProvider = ({ children }) => {
    const [isCartOpen, setIsCartOpen] = useState(false)
    const [cartProducts, setCartProducts] = useState([])
    const value = { isCartOpen, setIsCartOpen, cartProducts, setCartProducts };
    return (
        <CartContext.Provider value={value}>{children}</CartContext.Provider>
    )
}

产品环境

export const ProductsContext = createContext({
    currentProducts: null,
    setProducts: () => {}
})

export const ProductsProvider = ({children}) => {
    const [currentProducts, setProducts] = useState(shop_data)
    const value = {currentProducts, setProducts} 

    return(
        <ProductsContext.Provider value={value}>{children}</ProductsContext.Provider>
    )
}
kqlmhetl

kqlmhetl1#

您可以在每次要重新挂载时更换组件的关键道具。每次cartProduct更改时,更新key的值。您可以使用带有cartProduct作为依赖项的useEffect来实现这一点。

<CartDropdown key={1} />

<CartDropdown key={2} />

更多说明请编辑:

const [keyCount, setKeyCount] = useState(0);

useEffect(() => {
    setKeyCount(keyCount+1);
}, [cartProducts]);

<CartDropdown {...otherProps} key={keyCount} />

相关问题