如何确保没有依赖项的 useEffect 在 Ionic/React 中只调用一次?

问题描述 投票:0回答:2

我正在构建一个 Ionic 7、React 18 应用程序,但在理解基本的 useEffect 原理时遇到了一些困难。我有这个 App.tsx 文件

setupIonicReact();

const App: React.FC = () => {

  useEffect(() => {
    console.log("Loading user profile info in app..." + new Date().getUTCMilliseconds());
    UserService.getProfile()
      .then((user) => {
        console.log("User: " + JSON.stringify(user));
      })
      .catch((error) => {
        console.error("Error fetching profile:", error);
      });
  }, []);
  

  return (
    <IonApp>
      <IonReactRouter>
        <IonHeader>
          <IonToolbar>
            <IonButtons slot="start">
              <IonButton>
                <IonIcon icon={logoReact} />
              </IonButton>
            </IonButtons>
            <IonTitle>LOL Greetings</IonTitle>
            <IonButtons slot="end">
              <IonButton>
                <IonIcon icon={search} />
              </IonButton>
              <IonButton>
                <IonIcon icon={personCircle} />
              </IonButton>
            </IonButtons>
          </IonToolbar>
          <IonToolbar>
            <CategorySelectComponent />
          </IonToolbar>
        </IonHeader>

        <IonContent className="ion-padding" scroll-y>
        Test
        </IonContent>
      </IonReactRouter>
    </IonApp>
  );
};

export default App;

这是从我的 mainn.tsx 文件中调用的

const container = document.getElementById("root");
const root = createRoot(container!);
root.render(
  <React.StrictMode>
      <App />
  </React.StrictMode>
);

问题是我注意到“useEffect”被调用了两次(我可以看到对我的 UserProfile.getProfile”调用的两次调用。我如何确保它只被调用一次?我认为传递一个空的依赖项数组可以确保useEffect 只执行一次,但我想我错了。

reactjs ionic-framework react-hooks rendering
2个回答
0
投票

不用担心,既然您已经使用了

<StrictMode>
,您的组件将额外重新运行Effects一段时间,以查找因缺少Effect清理而导致的错误。在您的生产版本中,您的效果将仅运行一次

参见 https://react.dev/reference/react/StrictMode


0
投票

这是因为严格模式。它不会在生产构建中触发两次,但在开发模式下触发两次。它没有任何危险,但提供了一些好处来捕获一些错误。总而言之,不在乎:)

© www.soinside.com 2019 - 2024. All rights reserved.