我必須更新一定數量的產品。我已經使用 put 請求更新了資料庫中的資料,但在 UI 中,頁面需要重新加載才能看到更新的值。這是我的代碼
const ItemDetail = () => {
const { itemId } = useParams();
const [item, setItem] = useState({});
useEffect(() => {
const url = `https://ancient-garden-83535.herokuapp.com/item/${itemId}`;
fetch(url)
.then(res => res.json())
.then(data => setItem(data));
}, [])
//handle qantity deliver item
const handleDeliverd = () => {
const oldQuantity = parseInt(item.quantity)
const quantity = oldQuantity - 1;
const updatedQuantity = { quantity };
//send data to server
const url = `https://ancient-garden-83535.herokuapp.com/item/${itemId}`;
fetch(url, {
method: "PUT",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(updatedQuantity)
})
.then(res => res.json())
.then(result => {
console.log(result);
})
}
uj5u.com熱心網友回復:
嘗試在 useEffect 依賴陣列中添加專案狀態。
useEffect(()=>{your code here},[item])
uj5u.com熱心網友回復:
您需要使用setItem來導致渲染。每當狀態或道具發生變化時,React 組件會自動重新渲染
const handleDeliverd = () => {
const oldQuantity = parseInt(item.quantity)
const quantity = oldQuantity - 1;
const updatedQuantity = { quantity };
//send data to server
const url = `https://ancient-garden-83535.herokuapp.com/item/${itemId}`;
fetch(url, {
method: "PUT",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(updatedQuantity)
})
.then(res => res.json())
.then(result => {
// console.log(result);
setItem(result) // added setItems
})
}
uj5u.com熱心網友回復:
您可以創建一個輔助函式 fetchData 并在 useEffect 中使用它來首次獲取資料和放入新資料之后。
const ItemDetail = () => {
const { itemId } = useParams();
const [item, setItem] = useState({});
const fetchData = () => {
const url = `https://ancient-garden-83535.herokuapp.com/item/${itemId}`;
fetch(url)
.then(res => res.json())
.then(data => setItem(data));
}, [])
}
useEffect(() => {
fetchData()
}, [])
const handleDeliverd = () => {
const oldQuantity = parseInt(item.quantity)
const quantity = oldQuantity - 1;
const updatedQuantity = { quantity };
const url = `https://ancient-garden-83535.herokuapp.com/item/${itemId}`;
fetch(url, {
method: "PUT",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(updatedQuantity)
})
.then(res => res.json())
.then(result => { console.log(result) })
.then(fetchData)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470065.html
