我正在嘗試更新一個屬性 就像我有一些屬性、產品名稱、價格、數量、供應商和描述一樣。我將帶有所有屬性的所有更新數量發送到 MongoDb,在這種情況下,我可以更新資料庫和 UI 而無需任何重繪 。
const handleDelivered = (id) => {
const newQuantity = (quantity - 1);
if (newQuantity >= 0) {
const newService = {...serviceDetail, quantity: newQuantity}
setServiceDetail(newService);
const url = `https://intense-tor-77999.herokuapp.com/item/${id}`;
fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newService),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
})
}
else{
toast(`${productName} is sold out`);
}
}
但我只想更新一個屬性,例如只更新數量
const updateQuantity = { quantity : newQuantity};
那么,如何在不將所有屬性從前端發送到后端的情況下更新這一屬性?
uj5u.com熱心網友回復:
首先你可以宣告 const [isReload, setIsReload]= useState(true);
當您在上傳新數量后從資料庫獲得回應時,添加此
.then(response => response.json())
.then(data => {
console.log('Success:', data);
setIsReload(!isReload);
});
比你把 isReload 作為 useEffect 的依賴項,你通過 id 加載資料
useEffect(()=>{
fetch(url)
.then(res=>res.json())
.then(data => setData(data))
},[isReload ]);
嘗試一下
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470073.html
標籤:javascript 反应 mongodb 表示
上一篇:使用Node/React/MongoDB構建推薦系統
下一篇:無法安裝mongonode.js
