【发布时间】:2020-03-26 17:26:15
【问题描述】:
我正在尝试弄清楚如何让 Cloud Firestore 与 React 应用程序一起工作。
我找到了this tutorial,它使用实时数据库反应,并已加载。现在我正试图弄清楚我需要进行哪些更改才能使其与 Cloud Firestore 一起使用。
在我的 firebase.js 中,我有:
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import firestore from "firebase/firestore";
class Firebase {
constructor() {
app.initializeApp(config).firestore();
this.auth = app.auth();
// this.db = app.firebase.database()
this.db = app.firebase.firestore();
}
doCreateUserWithEmailAndPassword = (email, password) =>
this.auth.createUserWithEmailAndPassword(email, password);
doSignInWithEmailAndPassword = (email, password) =>
this.auth.signInWithEmailAndPassword(email, password);
doSignOut = () =>
this.auth.signOut();
doPasswordReset = email =>
this.auth.sendPasswordResetEmail(email);
doPasswordUpdate = password =>
this.auth.currentUser.updatePassword(password);
// *** User API ***
user = uid => this.db.ref(`users/${uid}`);
users = () => this.db.ref('users');
}
export default Firebase;
然后,以我的形式,我正在尝试:
import { withFirebase } from '../../../components/firebase';
onSubmit = event => {
const { username, email, passwordOne } = this.state;
this.props.firebase
.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(authUser => {
// Create a user
return this.props.firebase
.user(authUser.user.uid)
.set({
username,
email,
});
})
.then(authUser => {
this.setState({ ...INITIAL_STATE });
this.props.history.push(ROUTES.INITIAL_PROFILE);
})
.catch(error => {
this.setState({ error });
});
event.preventDefault();
}
onChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
与Firebase 的导入有:
import FirebaseContext, { withFirebase } from './Context';
import Firebase from '../../firebase.1';
export default Firebase;
export { FirebaseContext, withFirebase };
FirebaseContext 有:
import React from 'react';
const FirebaseContext = React.createContext(null);
export const withFirebase = Component => props => (
<FirebaseContext.Consumer>
{firebase => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
);
export default FirebaseContext;
当我尝试这个时,我收到一条错误消息:
TypeError:无法读取未定义的属性“firestore”
错误信息指向 firebase 配置文件的这一行:
this.db = app.firebase.firestore();
如何让 Firestore 在 React 应用中运行?
【问题讨论】:
-
app实际上是你的 firebase 实例,所以我猜你必须改为app.firestore()。
标签: javascript reactjs firebase google-cloud-firestore