Firebase onAuthStateChanged错误与React [英] Firebase onAuthStateChanged error with React

查看:80
本文介绍了Firebase onAuthStateChanged错误与React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Firebase检查用户是否已登录我的React网页,但是我一直收到错误 TypeError:无法读取未定义的属性'onAuthStateChanged',该行链接到的代码集如下:

I'm trying to check if a user is logged in or not on my React webpage using Firebase, however I keep getting an error TypeError: Cannot read property 'onAuthStateChanged' of undefined, the line of code it links to is as followed:

Login.js:

authListener() {
Fire.auth.onAuthStateChanged((user) => {
  if (user) {
    this.setState({ user })
  } else {
    this.setState({ user: null })
  }
})}

Fire.js:

import firebase from 'firebase'

const config = {
    apiKey: "xxx",
    authDomain: "xxx",
    databaseURL: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx",
    appId: "xxx"
};
const Fire = firebase.initializeApp(config);
export default Fire;

**解决了它,上面是我的Fire.js和Login.js对于那些遇到相同问题的人的样子**

** solved it, above is what my Fire.js and Login.js look like for those coming and having the same problem **

推荐答案

您需要包含firebase软件包

You need to include firebase package

import firebase from "firebase";

然后使用firebase的 auth()函数

and then use auth() function of firebase

authListener() {
firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    this.setState({ user })
  } else {
    this.setState({ user: null })
  }
})}

如果您要从另一个文件导入Firebase,则按以下方式进行配置

if you are importing firebase from another file then configure it like this

import firebase from 'firebase/app';
import 'firebase/auth';
export const init = () => {
    let config = {
        apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        authDomain: 'xxxxxxxxxxxxx'
    };
    firebase.initializeApp(config);
};

export const firebaseAuth = firebase.auth;

这篇关于Firebase onAuthStateChanged错误与React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆