简体   繁体   中英

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. 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.

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 .

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

setArray((state) =>
    state.map((x) =>
      x.id === id
        ? {
            ...x,
            newStock: x.newStock + 1,
          }
        : x,
    ),
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM