React 警告:在 useEffect 中更新狀態時,更新深度超過了最大限制
P粉447785031
P粉447785031 2023-09-06 13:46:55
0
1
572

我正在嘗試更新我的狀態變量,它是一個包含布林變量的物件。一旦資料可用(透過按鈕點擊呼叫的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粉447785031
P粉447785031

全部回覆(1)
P粉163465905

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,
      });
    }
  },[]);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板