简体   繁体   English

Function 在 jsx 中调用时更新 useState 钩子,导致无限循环

[英]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 work properly. 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 正常工作。 Below is my code下面是我的代码

My Function我的 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
    });
  }
}

My Jsx我的

{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}
                    />
                  } 
                  </>
                )
              }):
                <></> 
              }

Don't call a function which updates state on every render .不要调用 function ,它会在每次渲染时更新 state 。 Updating state triggers a re-render, so the component will endlessly re-render and re-invoke the function.更新 state 会触发重新渲染,因此组件将无休止地重新渲染并重新调用 function。

You're probably looking for the useEffect hook.可能正在寻找useEffect挂钩。 For example, to call the function once when the component first loads and then not again afterward, pass an empty dependency array to the hook:例如,要在组件首次加载时调用 function 一次,然后再不调用,请将一个空的依赖数组传递给钩子:

useEffect(() => {
  fetchDataFnc(booking);
}, []);

Though in this case booking is a dependency.虽然在这种情况下booking是一个依赖项。 To re-invoke the function any time that dependency changes, add it to the dependency array:要在依赖项更改时重新调用 function,请将其添加到依赖项数组中:

useEffect(() => {
  fetchDataFnc(booking);
}, [booking]);

As an aside, you also probably don't want to do all this inside the JSX .顺便说一句,您可能也不想在 JSX中执行所有这些操作。 The logic of the component, such as state and effects and helper functions, all happens before the JSX.组件的逻辑,例如 state 以及效果和辅助函数,都发生在 JSX 之前。 The JSX is the result returned by the component, which itself is a function like any other. JSX 是组件返回的结果,它本身就是一个 function 和其他的一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM