[英]Why is it that when I click the button containing the Up function, the item.newStock number is always one behind? (React)
I am making a small e-commerce site and am currently working on a shopping cart.我正在制作一个小型电子商务网站,目前正在开发购物车。 the idea is that every time I press the button containing the Up function, the array should change and then print on the screen via item.newStock.
这个想法是,每次我按下包含向上功能的按钮时,数组都应该改变,然后通过 item.newStock 在屏幕上打印。 However the first time I press the button it does nothing and the second time it adds one.
然而,我第一次按下按钮时它什么也不做,第二次它添加一个。 But when I console.log the number is one higher than what is printed via item.newStock.
但是当我使用 console.log 时,这个数字比通过 item.newStock 打印的数字高一。
Any ideas why that is happening?任何想法为什么会这样?
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,
),
);
}
Because setState
is asynchronous and buyQTY
will not have updated when you get to that setArray
.因为
setState
是异步的,当你到达那个setArray
时buyQTY
不会更新。
Honestly, I don't see the point in buyQTY
if each product should have its own quantity, so just get rid of it and do老实说,如果每种产品都应该有自己的数量,我看不出
buyQTY
有什么意义,所以把它去掉,然后做
setArray((state) =>
state.map((x) =>
x.id === id
? {
...x,
newStock: x.newStock + 1,
}
: x,
),
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.