我設定了這個組件,我使用全域背景關系來跟蹤我的購物車。但是,當 cartQty 更新時,我在螢屏上看不到更新的數量,只有當我重繪 頁面時。
const CartBody = () => {
const { cart, setCart } = useGlobalContext();
const increaseCartQty = (productName: any) => {
const index = cart.findIndex((product) => product.name === productName);
cart[index].quantity = cart[index].quantity 1;
setCart(cart);
};
return (<div>{cart.quantity}</div>)
}
uj5u.com熱心網友回復:
您正在改變狀態而不是創建新狀態。當您在功能組件中設定狀態時,react 會===在舊狀態和新狀態之間進行。如果它們相等,則跳過渲染。
改為這樣做:
const increaseCartQty = (productName: any) => {
const index = cart.findIndex((product) => product.name === productName);
const newCart = [...cart];
newCart[index] = {
...cart[index],
quantity: cart[index].quantity 1,
};
setCart(newCart);
};
要么:
const increaseCartQty = (productName: any) => {
const newCart = cart.map((product) => {
return product.name === productName
? {
...product,
quantity: product.quantity 1,
}
: product;
});
setCart(newCart);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/453266.html
