[英]On clicking a button to add elements to an array in javascript, each time console.logging the array is returned with one less element
On, clicking a button to add an item to an array initialised as cart, the added item immediately appears in the cart array however, when I console.log the array, the item added does not get shown until after the next click.在,单击一个按钮将项目添加到初始化为购物车的数组中,添加的项目立即出现在购物车数组中,但是,当我 console.log 数组时,添加的项目直到下一次点击后才会显示。 In that the first time the add button is clicked and the cart array console.logged;
在第一次单击添加按钮时,购物车数组 console.logged; an empty array is returned.
返回一个空数组。 On the second click, the cart array is returned with only one item, the one supposedly added on the first click and so on, yet when I call a map method on the cart array, all the added elements are present.
在第二次单击时,购物车数组只返回一个项目,即第一次单击时应该添加的项目,依此类推,但是当我在购物车数组上调用 map 方法时,所有添加的元素都存在。 Why does it seem as though there is a delay?
为什么好像有延迟?
const [cart, setCart] = useState([]);
const addItem = (prod, index) => {
setCart([...cart, prod]);
console.log(cart);//seems to have a delay, one less item featured each click
};
return (
<>
<div className="cartItems">
{cart.map((prod, index) => {
return (
<div key={prod.id} className="">
<h2 className="itemTitle">{prod.name}</h2>
</div>
);
})}
</div>
<div className="itemsContainer">
{products.map((prod, index) => {
return (
<div key={prod.id} className="itemContainer">
<img
src={prod.src}
alt={prod.name}
className="itemImage"
/>
<h2 className="itemTitle">{prod.name}</h2>
<span className="itemPrice">{prod.priceN}</span>
<button
className="itemButton"
onClick={() => {
addItem(prod, index);
}}
>
Order
</button>
</div>
);
})}
</div>
</>
);
You can't get the correct value from state variable after setting it up.设置后无法从 state 变量中获取正确的值。
You updated your state value cart
by setCart([...cart, prod]);
您通过
setCart([...cart, prod]);
更新了您的 state 价值cart
车; . . Then you tried to print
cart
at the next line.然后您尝试在下一行打印
cart
。
const addItem = (prod, index) => {
setCart([...cart, prod]);
console.log(cart);//seems to have a delay, one less item featured each click
};
But it doesn't work.但它不起作用。 Because setState works asynchronously in React.
因为 setState 在 React 中是异步工作的。
Here is the statement in Reactjs official document.这是Reactjs官方文档中的说法。
State Updates May Be Asynchronous
State 更新可能是异步的
React may batch multiple setState() calls into a single update for performance.
React 可以将多个 setState() 调用批处理到单个更新中以提高性能。
Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
因为 this.props 和 this.state 可能会异步更新,所以你不应该依赖它们的值来计算下一个 state。
To know the updated state value, please use useEffect
hook.要知道更新后的 state 值,请使用
useEffect
hook。
You can print the updated state value like the following:您可以打印更新后的 state 值,如下所示:
useEffect(() => {
console.log(cart);
}, [cart]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.