搜尋

首頁  >  問答  >  主體

React 警告:在 useEffect 中更新狀態時,更新深度超過了最大限制

我正在嘗試更新我的狀態變量,它是一個包含布林變量的物件。一旦資料可用(透過按鈕點擊呼叫的API呼叫回應),我就在useEffect內部更新我的狀態。然後使用這些資料呼叫另一個元件,即一個模態框,如果沒有資料可用,我將顯示另一個模態框。當我關閉彈出視窗時,應該更新狀態變數。

const [modalState, setModalState] = useState<IModalState>({
  showNoUsersModal: false,
  showModal: false,
});

useEffect(() => {
  if (data && data.length > 0) {
    setModalState({
      ...modalState,
      showModal: true,
      showNoUsersModal: false,
    });
  } else if (data && data.length === 0) {
    setModalState({
      ...modalState,
      showModal: false,
      showNoUsersModal: true,
    });
  }
});

const onApplicationSuccess = () => {
  setModalState({
    ...modalState,
    showModal: false,
    showNoUsersModal: false,
  });
}

const onClose = () => {
  setModalState({
    ...modalState,
    showModal: false,
    showNoUsersModal: false,
  });
}

return (
  <div>
    {modalState.showNoUsersModal && (
      <NoUsersFoundModal
        onCancel={() =>
          setModalState({
            ...modalState,
            showModal: false,
            showNoUsersModal: false,
          })
        }
      />
    )}

    {modalState.showModal && (
      <SomeOtherModal
        onCancel={() =>
          setModalState({
            ...modalState,
            showModal: false,
            showNoUsersModal: false,
          })
        }
      />
    )}
  </div>
)
P粉447785031P粉447785031434 天前547

全部回覆(1)我來回復

  • P粉163465905

    P粉1634659052023-09-07 00:06:51

    this issue was because you didn't pass any dependency array to useEffect so when ever state was changing useEffect was calling again. here is the solution .

    useEffect(() => {
        if (data && data.length > 0 ) {
          setModalState({
            ...modalState,
            showModal: true,
            showNoUsersModal: false,
          });
        } else if (data && data.length == 0) {
          setModalState({
            ...modalState,
            showModal: false,
            showNoUsersModal: true,
          });
        }
      },[]);

    這個問題是因為你沒有傳遞任何依賴數組給 useEffect,所以每當狀態改變時 useEffect 就會再次呼叫。這裡是解決方案。

    useEffect(() => {
        if (data && data.length > 0 ) {
          setModalState({
            ...modalState,
            showModal: true,
            showNoUsersModal: false,
          });
        } else if (data && data.length == 0) {
          setModalState({
            ...modalState,
            showModal: false,
            showNoUsersModal: true,
          });
        }
      },[]);

    回覆
    0
  • 取消回覆