React 警告:在 useEffect 中更新状态时,更新深度超过了最大限制
P粉447785031
P粉447785031 2023-09-06 13:46:55
0
1
555

我正在尝试更新我的状态变量,它是一个包含布尔变量的对象。一旦数据可用(通过按钮点击调用的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,
      });
    }
  },[]);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板