简体   繁体   English

如何减少 react.js 和 node.js 中的数量

[英]How to reduce quantity in react.js and node.js

react.js As you can see in the react code, I am trying to reduce the quantity, but I struggle to do it in react. react.js正如你在反应代码中看到的那样,我试图减少数量,但我很难在反应中做到这一点。 what I want is if click button then quantity should be reduced 1 by 1. I think I am我想要的是如果单击按钮,那么数量应该减少 1。我想我是

const [quantity, setQuantity] = useState(0)

const handleDelivery = event => {
  event.preventDefault();

  const deliveryInventoryItem = inventoryItem.quantity(quantity-1);

  const url = `http://localhost:5000/inventoryItem/${inventoryItemId}`;

  fetch(url, {
    method: 'PUT',
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify(deliveryInventoryItem)
  })
    .then(res => res.json())
    .then(data => {
    console.log('success', data);
    alert('users added successfully!');
    event.target.reset();
    setQuantity(data)
  })

}

node.js节点.js

app.put('/inventoryItem/:id', async (req, res) => {
  const id = req.params.id;

  const deliveryInventoryItem = req.body;
  console.log(id, updatedInventoryItem);
  const filter = {_id: ObjectId(id)};
  const options = {upsert: true};
  const updatedDoc = {
    $set: {
      quantity: deliveryInventoryItem.quantity
    }
  };
  const result = await inventoryItemCollection.updateOne(filter, updatedDoc, options);
  res.send(result);

})

In mongoDB, use $inc to increase or descrease quantity, see more: MongoDB $inc docs在 mongoDB 中,使用 $inc 来增加或减少数量,查看更多: MongoDB $inc docs

In React app:在反应应用程序中:

const quantityChange = -1 // If you want decrease 1 by 1 or any number you want increase or decrease by this number
fetch(url, {
  method: 'PUT',
  headers: {
    'content-type': 'application/json'
   },
  body: JSON.stringify(quantityChange)
}).then().catch()
...

In Nodejs App, edit your updatedDoc:在 Nodejs App 中,编辑您的 updatedDoc:

const { quantityChange } = res.body
const updatedDoc = {
    $inc: {
      quantity: quantityChange
    }
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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