gpt4 book ai didi

javascript - 将 React 与 Cloud Firestore 结合使用

转载 作者:行者123 更新时间:2023-12-01 00:24:32 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何让 Cloud Firestore 与 React 应用程序一起使用。

我找到了this tutorial ,它使用实时数据库进行 react ,并已加载它。现在我正在尝试找出需要进行哪些更改才能使其与 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 });
};

导入 withFirebase 具有:

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;

当我尝试此操作时,我收到一条错误消息:

类型错误:无法读取未定义的属性“firestore”

错误消息指向 firebase 配置文件的这一行:

this.db = app.firebase.firestore();

如何让 firestore 在 React 应用程序中工作?

最佳答案

更改此:

this.db = app.firebase.firestore();

进入此:

this.db = app.firestore();

initializeApp()返回类型 App,在 App 中您可以找到方法 firestore():

https://firebase.google.com/docs/reference/js/firebase.app.App.html#firestore

关于javascript - 将 React 与 Cloud Firestore 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59133170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com