Firebase为什么被初始化两次?

huangapple go评论65阅读模式
英文:

Why is firebase being initialized twice?

问题

我在React应用程序运行时初始化Firebase。由于我在组件挂载时调用initFirebase,所以它应该只被调用一次。但在控制台中,我看到"Initialized firebase app"出现了两次。为什么这个函数运行了两次?

相关的代码:

function App() {
  const [FBApp, setFBApp] = useState(null);

  useEffect(() => {
    let app = initFirebase();
    setFBApp(app);  
  }, [])

  const router = createBrowserRouter([{
    path: "/",
    element: <HomePage />
  },
  {
    path: "/admin",
    element: <AdminPage />
  }
])

  return (
    <FirebaseAppContext.Provider value={{FBApp, setFBApp}}>
      <RouterProvider router={router} />
    </FirebaseAppContext.Provider>
  )
}


//initFirebase.js
import { initializeApp } from "firebase/app";

const initFirebase = () => {
  const firebaseConfig = {
    apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
    authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
    projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
    storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
    appId: import.meta.env.VITE_FIREBASE_APP_ID,
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  console.log("Initialized firebase app", app);
  return app;
};

export default initFirebase;
英文:

I'm initializing firebase when the react app runs. Since I'm calling initFirebase on component mount, it should be called only once. But in my console, I see "Initialized firebase app" twice. Why is the function runnning twice?

The relevant code:

function App() {
  const [FBApp, setFBApp] = useState(null);

  useEffect(() =&gt; {
    let app = initFirebase();
    setFBApp(app);  
  }, [])

  const router = createBrowserRouter([{
    path: &quot;/&quot;,
    element: &lt;HomePage /&gt;
  },
  {
    path: &quot;/admin&quot;,
    element: &lt;AdminPage /&gt;
  }
])

  return (
    &lt;FirebaseAppContext.Provider value={{FBApp, setFBApp}}&gt;
      &lt;RouterProvider router={router} /&gt;
    &lt;/FirebaseAppContext.Provider&gt;
  )
}


//initFirebase.js
import { initializeApp } from &quot;firebase/app&quot;;

const initFirebase = () =&gt; {
  const firebaseConfig = {
    apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
    authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
    projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
    storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
    appId: import.meta.env.VITE_FIREBASE_APP_ID,
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  console.log(&quot;Initialized firebase app&quot;, app);
  return app;
};

export default initFirebase;

答案1

得分: 2

initFirebase函数运行两次是因为您正在使用React 18和StrictMode。React 18在使用StrictMode时,引入了useEffect在开发模式下的默认行为更改。StrictMode是一个工具,通过激活额外的检查和警告,帮助您找到应用中潜在的问题。其中一个检查是在挂载和卸载时将组件渲染两次,这也导致useEffect运行两次。这是为了检测任何未正确清理或依赖于渲染顺序的副作用。要了解更多信息,请参阅为什么useEffect运行两次?- flaviocopes.com

为了避免运行两次,您可以在useEffect钩子中使用清理函数。

例如:

useEffect(() => {
  let app = initFirebase();
  setFBApp(app);
  return () => {
    app.delete();
  };
}, []);
英文:

initFirebase function is running twice because you are using React 18 and StrictMode. React 18 introduced a change in the default behavior of useEffect in development mode when using StrictMode. StrictMode is a tool that helps you find potential problems in your app by activating additional checks and warnings. One of these checks is to render the component twice on mount and unmount, which causes useEffect to run twice as well. This is done to detect any side effects that are not properly cleaned up or depend on the render order. To learn more, see Why does useEffect run two times? - flaviocopes.com

To avoid running twice, you can use cleanup function in useEffect hook.

For example:

useEffect(() =&gt; {
  let app = initFirebase();
  setFBApp(app);
  return () =&gt; {
    app.delete();
  };
}, []);

答案2

得分: 0

从index.js中删除<React.StrictMode>。此代码将是

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

React StrictMode会两次渲染组件。

还有一个可能的原因是此代码触发了父组件的重新渲染,从而使其运行两次。

英文:

Remove <React.StrictMode> from index.js This code will be

root.render(
  &lt;React.StrictMode&gt;
    &lt;App /&gt;
  &lt;/React.StrictMode&gt;
);

React StrictMode renders components twice.

one more reason can be this code is triggering re-render in parent component that is making it run it twice.

huangapple
  • 本文由 发表于 2023年7月10日 15:00:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定