我在哪里在React应用程序中初始化Firebase应用程序? [英] Where do I initialize Firebase app in React application?
问题描述
我正在尝试将Firebase集成到我的React应用程序中,在查看了各种教程之后,我似乎找不到关于将Firebase初始化代码firebase.initializeApp(config)
放置在何处的共识.
I'm trying to integrate Firebase into my React app and after looking at various tutorials, I can't seem to find a consensus on where to put the firebase initialization code firebase.initializeApp(config)
.
我的应用程序的结构是这样的:
My app's structure is this:
- app.js
- components
|___Index.jsx
|___Layout.jsx
|___PageContent.jsx
每个文件如下所示
app.js
使用服务器端渲染完成所有快速设置
Does all the express setup with server-side rendering
Index.jsx
import React from 'react';
import Layout from './Layout.jsx';
import PageContent from './PageContent.jsx';
import './global.css';
class Index extends React.Component {
render() {
return (
<Layout title={this.props.title}>
<PageContent />
</Layout>
);
}
}
export default Index;
PageContent.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import LandingPage from './components/Landing_Page/Landing.jsx';
class PageContent extends React.Component {
render() {
return (
<LandingPage />
);
}
}
if (typeof window !== 'undefined') {
ReactDOM.render(
<PageContent />,
document.getElementById('root')
);
}
export default PageContent;
我需要确保Firebase在我网站的每个页面中都可用.现在它是一个单页应用程序,但最终我会添加更多.
I need to make sure Firebase is available in every page of my website. Right now it is a single page app but eventually I'll be adding more.
有人可以帮助我了解将数据库初始化代码放在哪里,以便将其应用于所有地方吗?
Can anybody help me understand where I might put the database initialization code so that it is applied everywhere?
推荐答案
这就是我的方法
在app.js
旁边创建文件Firebase.js
并放置您的初始化代码
create file Firebase.js
next to app.js
and put your initialization code
Firebase.js文件
Firebase.js file
import * as firebase from 'firebase';
let config = {
apiKey: "XXXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXX"
};
firebase.initializeApp(config);
export default firebase;
,然后在每个要使用的位置导入Firebase.js
文件,例如
and then import Firebase.js
file every where you want to use it , for example
import React from 'react';
import firebase from './../Firebase.js' // <------ import firebase
class Test extends React.Component {
componentDidMount(){
firebase.database().ref().child("X").on('value' , {...});
}
render() {
return (
<h1>Hello</h1>
);
}
}
export default Test;
这篇关于我在哪里在React应用程序中初始化Firebase应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!