简体   繁体   English

单击按钮将元素添加到 javascript 中的数组时,每次 console.logging 返回数组时都会少一个元素

[英]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.

相关问题 Console.logging 然后在 javascript 函数中返回 console.log - Console.logging and then returning the console.log within a javascript function 如何设置在控制台记录数组时记录的 class object 的值? - How can I get set the value of a class object that logs when console.logging an array? 如何使用javascript或angular将一个数组的每个元素添加到其他数组中的对应元素 - How can I add each element of one array to corresponding elements in other arrays with javascript or angular 对于未知数量的元素,尝试将数组的每个元素添加到下一个元素 - Trying to add each element of array to the next one for unknown number of elements 以0开头的console.logging数字 - console.logging numbers starting with 0 Javascript 数组返回元素,但是当记录长度时我得到零 - Javascript array returned with elements but when logging length I get zero 将时间元素添加到javascript数组 - Add time element to javascript array 单击按钮时,一个接一个地遍历数组元素 - Iterate through array elements one by one when clicking on button 单击下一步按钮时如何一一显示数组的元素? - how to display elements of array one by one on clicking next button? javascript:切换多维数组中每个元素的元素 - javascript: switch elements of each element in multidimensional array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM