【问题标题】:How to check if user authenticated using firebase in react如何检查用户是否在反应中使用firebase进行了身份验证
【发布时间】:2019-09-23 10:53:52
【问题描述】:

我在 react 项目中有多个页面,包括 signin.js 和 signup.js。 在我的登录页面中,我可以登录并查看用户详细信息。但是当我切换到注册页面时,我无法在此代码中使用{user}
我也想在注册页面中查看登录的用户详细信息。有人可以帮忙解开这个谜。 我是反应 js 的新手。

signin.js
import React from 'react'
import withFirebaseAuth from 'react-with-firebase-auth'
import firebaseConfig from './firebaseConfig'
import * as firebase from 'firebase/app';
import 'firebase/auth';
const firebaseApp = firebase.initializeApp(firebaseConfig);

class signin extends React.Component {
    state = {
        email :'',
        password:''
    }
    handleChange = (e) => {
        this.setState({
            [e.target.id] : e.target.value
        })
    }

    handleSubmit = (e) => {
        e.preventDefault()
        firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password).catch(function(error) {
            console.log(error.code)
            console.log(error.message)
            if(error.code == 'auth/invalid-email') {
                alert("The email you have entered is in incorrect format")
            }
            else if(error.code == "auth/wrong-password"){
                alert("The password you have entered is incorrect")
            }
            else if(error.code == "auth/user-not-found") {
                alert("Email not found")
            }
            else if(error.code == "auth/too-many-requests"){
                alert("Too many requests.  Please try again after some time .")
            }
            else {
                alert(error.message)
            }
           })
    }
    render() {
        const {
            user,
            signOut,
            signInWithGoogle,
          } = this.props;

        return (
            <div>
                Signin
                <div className="container">  
                {
                    user 
                        ? <div><p>Hello, {user.displayName}</p>
                        <p>You profile :</p><img src={user.photoURL} width="50px" height="50px"></img><p>Your email : {user.email}</p></div>
                :         
                    <form onSubmit={this.handleSubmit} className="white">
                        <div className="input-field">
                            <label htmlFor="email"> Email</label>
                            <input type = "text" id="email" onChange={this.handleChange}></input>
                        </div>
                        <div className="input-field">
                            <label htmlFor="password"> Password</label>
                            <input type="password" id ="password" onChange={this.handleChange}></input>
                        </div>
                        <div className="input-field">
                            <button  className ="btn pink lighten-2 z-depth-0">Login</button> 
                        </div>
                    </form>
                }
                {/* {
            user
              ? <div><p>Hello, {user.displayName}</p><p>Your email : {user.email}</p></div>
              : <p>Please sign in.</p>
          } */}

          {
            user
              ? <button className="btn blue lighten-2 z-depth-0" onClick={signOut}>Sign out</button>
              : <button className="btn blue lighten-2 z-depth-0" onClick={signInWithGoogle}>Sign in with Google</button>
          }
            </div>
            </div>
        )
    }
}
const firebaseAppAuth = firebaseApp.auth();
const loginAuth = firebaseApp.auth().signInWithEmailAndPassword;
const providers = {
  googleProvider: new firebase.auth.GoogleAuthProvider(),
};

export default withFirebaseAuth({
  providers,
  firebaseAppAuth,
  loginAuth,
})(signin);
signup.js
import React from 'react'
import * as firebase from 'firebase/app';
import 'firebase/auth';
export default class signup extends React.Component {
    state = {
        email :'',
        password:'',
        firstName:'',
        lastName:''
    }
    handleChange = (e) => {
        this.setState({
            [e.target.id] : e.target.value
        })
    }

    handleSubmit = (e) => {
        e.preventDefault()
        console.log(this.state)
        firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((user) => {
            console.log(user)}).catch(function(error) {
            alert('Error :'+error.message);
           })
    }
    render() {
        return (
            <div>
            SignUp
            <div className="container">
                <form onSubmit={this.handleSubmit} className="white">
                    <div className="input-field">
                        <label htmlFor="FirstName"> First Name</label>
                        <input type = "text" id="firstName" onChange={this.handleChange}></input>
                    </div>
                    <div className="input-field">
                        <label htmlFor="lastName"> Last Name</label>
                        <input type = "text" id="lastName" onChange={this.handleChange}></input>
                    </div>
                    <div className="input-field">
                        <label htmlFor="email"> Email</label>
                        <input type = "text" id="email" onChange={this.handleChange}></input>
                    </div>
                    <div className="input-field">
                        <label htmlFor="password"> Password</label>
                        <input type="text" id ="password" onChange={this.handleChange}></input>
                    </div>
                    <div className="input-field">
                        <button  className ="btn pink lighten-2 z-depth-0">Signup</button> 
                    </div>
                </form>
            </div>
            </div>
        )
    }
}

【问题讨论】:

  • 您可以将数据保存在本地存储中,登录后您可以在项目的任何地方访问本地存储
  • @AmitRai 嗨,谢谢。我是反应 js 的新手。我可以使用 state 或任何其他东西来做吗?你能指定它吗?

标签: reactjs firebase react-native react-router


【解决方案1】:

您可以在componentDidMount() 中添加此功能,以检查您的用户是否已经登录。 如果您需要在应用程序的其他点访问此用户信息,我建议将任何与身份验证有关的逻辑分离到一个单独的组件中,然后使用 reduxcontextApi 或简单地作为道具传递数据应用的其余部分。

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    var displayName = user.displayName;
    var email = user.email;
    var emailVerified = user.emailVerified;
    var photoURL = user.photoURL;
    var isAnonymous = user.isAnonymous;
    var uid = user.uid;
    var providerData = user.providerData;
    // ...
  } else {
    // User is signed out.
    // ...
  }
});

【讨论】:

  • 没用。你能解释一下吗?或者我该如何使用 componentDidmount() ?
  • componentDidMount 是 React 类的生命周期方法。基本上它只会在你的组件第一次渲染之后执行一段代码。查看我的其他答案以获取编码示例。
【解决方案2】:

一旦你的组件第一次被渲染,componentDidMount 就会运行。如果您的用户已登录,onAuthStateChanged 函数将有权访问包含您用户信息的 {user}。然后,您可以将此信息保存到您的组件状态,例如通过 this.setState({email:user.email})。

class signin extends React.Component {
        state = {
            email :'',
            password:''
        }
    
      componentDidMount() {
        firebase.auth().onAuthStateChanged(function (user) {
            if (user) {
                console.log(user)
                this.setState({email:user.email})
            }
    
        }
    
        handleChange = (e) => {
            this.setState({
                [e.target.id] : e.target.value
            })
        }

【讨论】:

    猜你喜欢
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2018-12-28
    • 2021-09-22
    相关资源
    最近更新 更多