[英]ReactJS UI Does Not Update The State
我正在嘗試制作一個簡單的電子商務應用程序。 當用戶進入購物車部分並嘗試增加或減少數量時,它會更改狀態但在頁面上保持不變。 我需要回去再去購物車更新。 它如何動態變化?
function CardItem() {
const {cart, setCart} = useContext(ProductContext)
const addQuantity = (cartItem) => {
return cart.map((item) => (
cartItem.id === item.id ? item.quantity = item.quantity + 1 : item
))
}
const removeQuantity = (cartItem) => {
cart.map((item) => (
cartItem.id === item.id ? item.quantity = item.quantity - 1 : item
))
}
return (
{
cart.map((cartItem) => (
<tr key={cartItem.id}>
<td class="quantity__item">
<div class="quantity">
<div class="pro-qty-2 d-flex align-items-center justify-content-center text-center">
<button className='increase' onClick={() => removeQuantity(cartItem)}>
-</button>
{cartItem.quantity}
<button className='increase' onClick={() => addQuantity(cartItem)}>+</button>
</div>
</div>
</td>
</tr>
))
})}
setCart
來更新任何狀態。cart
狀態對象。 不要改變 React 狀態。使用setCart
狀態更新器函數將狀態更新排入隊列以觸發重新渲染以查看更新后的狀態。 使用功能狀態更新從先前的狀態正確更新,並記住您應該淺拷貝任何正在更新的狀態。
例子:
function CardItem() {
const { cart, setCart } = useContext(ProductContext);
const addQuantity = (cartItem) => {
setCart(cart => cart.map(item => cartItem.id === item.id
? { // <-- new item object reference
...item, // <-- shallow copy item
quantity: item.quantity + 1, // <-- update property
}
: item
));
};
const removeQuantity = (cartItem) => {
setCart(cart => cart.map(item => cartItem.id === item.id
? {
...item,
quantity: item.quantity - 1,
}
: item
));
};
return (
{cart.map((cartItem) => (
<tr key={cartItem.id}>
<td class="quantity__item">
<div class="quantity">
<div class=" .... ">
<button className='increase' onClick={() => removeQuantity(cartItem)}>
-
</button>
{cartItem.quantity}
<button className='increase' onClick={() => addQuantity(cartItem)}>
+
</button>
</div>
</div>
</td>
</tr>
))
});
}
由於添加/刪除本質上是相同的操作,因此通常使用單個函數來處理兩者並傳遞您想要調整的數量。
function CardItem() {
const { cart, setCart } = useContext(ProductContext);
const addQuantity = (id, amount) => () => {
setCart(cart => cart.map(item => cartItem.id === id
? {
...item,
quantity: item.quantity + amount,
}
: item
));
};
return (
{cart.map((cartItem) => (
<tr key={cartItem.id}>
<td class="quantity__item">
<div class="quantity">
<div class=" .... ">
<button
className='increase'
onClick={addQuantity(cartItem.id, -1)}
>
-
</button>
{cartItem.quantity}
<button
className='increase'
onClick={addQuantity(cartItem.id, 1)}
>
+
</button>
</div>
</div>
</td>
</tr>
))
});
}
我會推薦使用帶有上下文的 reducer 來管理狀態。 類似於下面的帶有 ADD 和 REMOVE 項目等操作的新 CartReducer
const [state, dispatch] = useReducer(CartReducer, initalState);
const addToCart = (id) => {
dispatch({ type: ADD, payload: id});
};
const showHideCart = () => {
dispatch({ type: SHOW, payload:'' });
};
const removeItem = (id) => {
dispatch({ type: REMOVE, payload: id });
};
如果它有助於購物車與上下文 API,你可以參考這個項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.