【发布时间】:2022-08-02 19:29:13
【问题描述】:
我有一个获取数据并更新 useState 钩子的函数,但是当我在 jsx 中调用该函数时,它会导致一个无限循环,我曾尝试在 jsx 中放置一个条件,然后再调用该函数以避免无限循环,但随后该函数不会\不能正常工作。下面是我的代码
我的功能
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}
/>
}
</>
)
}):
<></>
}
-
你能完成你的代码,并添加 useState 声明以提供清晰...
-
您应该在渲染阶段之外调用您的函数。尝试在 useEffect 中调用它,例如:作为选择预订的副作用,如果这有意义:) 这是反应文档的链接
标签: javascript reactjs