![](/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.