![](/img/trans.png)
[英]When I console.log a user's radio button selection, what logs is always one behind
[英]Why is it that when I click the button containing the Up function, the item.newStock number is always one behind? (React)
我正在制作一個小型電子商務網站,目前正在開發購物車。 這個想法是,每次我按下包含向上功能的按鈕時,數組都應該改變,然后通過 item.newStock 在屏幕上打印。 然而,我第一次按下按鈕時它什么也不做,第二次它添加一個。 但是當我使用 console.log 時,這個數字比通過 item.newStock 打印的數字高一。
任何想法為什么會這樣?
const Table = () => {
return (
<div class="container">
<table class="table m-4">
<thead>
<tr>
<th scope="col">Cake</th>
<th scope="col">QTY</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
{array.map((item) => {
if (item.newStock > 0) {
return (
<>
<tr>
<th scope="row">{item.title}</th>
<td>{item.newStock}</td>
<td>${item.price}</td>
<div class="changeQTY">
<h5>QTY</h5>
<button class="up" onClick={Up}>
+
</button>
<button class="down">
<span class="minus">-</span>
</button>
<button>Delete</button>
</div>
</tr>
</>
);
}
})}
</tbody>
</table>
<button>Confirm Purchase</button>
</div>
);
};
function Up() {
setBuyQTY(parseInt(buyQTY) + 1);
setArray((state) =>
state.map((x) =>
x.id === id
? {
...x,
newStock: parseInt(buyQTY),
}
: x,
),
);
}
因為setState
是異步的,當你到達那個setArray
時buyQTY
不會更新。
老實說,如果每種產品都應該有自己的數量,我看不出buyQTY
有什么意義,所以把它去掉,然后做
setArray((state) =>
state.map((x) =>
x.id === id
? {
...x,
newStock: x.newStock + 1,
}
: x,
),
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.