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



react.js正如您在react代码中看到的,我试图减少数量,但在react中很难做到。我想要的是,如果点击按钮,那么数量应该减少1乘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

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);
})

在mongoDB中,使用$inc来增加或减少数量,请参阅更多:mongoDB$inc docs

在React应用程序中:

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

在Nodejs应用程序中,编辑您更新的文档:

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

最新更新