英文:
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(() => {
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;
答案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(() => {
let app = initFirebase();
setFBApp(app);
return () => {
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(
<React.StrictMode>
<App />
</React.StrictMode>
);
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论