搜索

首页  >  问答  >  正文

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粉447785031447 天前557

全部回复(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
  • 取消回复