![](/img/trans.png)
[英]useNavigate hook called inside useEffect causing infinite loop
[英]Function that updates a useState hook when called in jsx it is causing an infinite loop
I have a function that fetches data and updates a useState hook but when i call that function inside jsx it causes an infinite loop, I have tried to put a condition in jsx before i call the function to avoid infinite loop but then the function doesn' t 正常工作。 下面是我的代碼
我的 Function
const fetchDataFnc = (booking) => {
const fleetId = booking.booking_bids_fleet_id
const bookingId = booking.booking_id
console.log("fleetId" ,fleetId)
if(booking.booking_bids_fleet_id){
firebase.database().ref('fleets/' +
fleetId[0]).child("booking_bids").child(bookingId).on('value', (snapshot) => {
console.log("fleet snap",snapshot.val())
setFirstPrice(snapshot.val().price[0])
setAllPrices(snapshot.val().price)
console.log("all the prices", snapshot.val().price)
console.log("fleet collect", snapshot.val());
});
}
if(booking.booking_bids_fleet_id){
firebase.database().ref('booking/' + bookingId).child("booking_bids_prices").set({
firstPrice
});
}
}
我的
{selectedBooking.length > 0 ? selectedBooking.map((booking)=>{
// showFirstPrice(booking)
if(Math.random() > 0.5) {
fetchDataFnc(booking)
}
return(
<>
{firstSel &&
<SelectedBooking
booking_ref={booking.booking_ref}
firstPrice={firstPrice}
booking={booking}
handleSettle={handleSettle}
setSettleAmount={setSettleAmount}
settleAmount={settleAmount}
allPrices={allPrices}
handleAccept={handleAccept}
/>
}
</>
)
}):
<></>
}
不要調用 function ,它會在每次渲染時更新 state 。 更新 state 會觸發重新渲染,因此組件將無休止地重新渲染並重新調用 function。
您可能正在尋找useEffect
掛鈎。 例如,要在組件首次加載時調用 function 一次,然后再不調用,請將一個空的依賴數組傳遞給鈎子:
useEffect(() => {
fetchDataFnc(booking);
}, []);
雖然在這種情況下booking
是一個依賴項。 要在依賴項更改時重新調用 function,請將其添加到依賴項數組中:
useEffect(() => {
fetchDataFnc(booking);
}, [booking]);
順便說一句,您可能也不想在 JSX中執行所有這些操作。 組件的邏輯,例如 state 以及效果和輔助函數,都發生在 JSX 之前。 JSX 是組件返回的結果,它本身就是一個 function 和其他的一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.