如何解决在ReactJS中使用Firebase数据库时出现Firebase JS SDK警告
我正在尝试将Firebase数据库用于我的项目,但无法正确导入和使用该模块。我遵循了官方文档的建议。
这是我使用它的代码。
import React from "react";
import firebase from "firebase";
import ProjectItemCards from "./components/project-item-cards";
const ProjectContext = React.createContext();
class ProjectProvider extends React.Component {
constructor() {
super();
this.state = {
social: {},projects: [],featuredProjects: [],loading: true,};
}
componentDidMount() {
var ref = firebase.database().ref("projects");
ref.on("value",(snapshot) => {
const projects = snapshot.val();
console.log(projects);
const featuredProjects = projects
.map((project) => (project.featured === true ? project : null))
.slice(0,4);
this.setState({
projects,featuredProjects,loading: false,});
});
}
getProjectElements(projects) {
const projectElementList = projects.map((project,index) => {
return (
<ProjectItemCards key={index} project={project}></ProjectItemCards>
);
});
return projectElementList;
}
render() {
return (
<ProjectContext.Provider
value={{ ...this.state,getProjectElements: this.getProjectElements }}
>
{this.props.children}
</ProjectContext.Provider>
);
}
}
export { ProjectProvider,ProjectContext };
我已经按照以下方式初始化了firebase
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "bootstrap";
import "./sass/main.scss";
import * as firebase from "firebase/app";
import "firebase/analytics";
var firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,authDomain: "",databaseURL: "",projectId: "",storageBucket: "",messagingSenderId: "",appId: "1:841600272388:web:12314d1260dded0601cd51",measurementId: "G-55E4QT6C4F",};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
ReactDOM.render(<App />,document.getElementById("root"));
我已从上述代码中删除了所有敏感信息 还要注意,我正在根据需要获取数据,并且一切正常。我只是想摆脱这个警告
解决方法
初始化代码应在实用程序文件中使用,并应如下所示:
import * as firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/storage'
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,appId: process.env.REACT_APP_FIREBASE_APP_ID
}
firebase.initializeApp(firebaseConfig)
export const db = firebase.firestore()
export const storage = firebase.storage()
export default firebase
您要导出正在使用的单个Firebase功能。在您的情况下,我假设使用firebase.firestore
然后您的导入应如下所示:
import {db} from '../utils/firebase'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。