首页 > 解决方案 > 如何检查用户是否在反应中使用firebase进行了身份验证

问题描述

我在 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>
        )
    }
}

标签: reactjsfirebasereact-nativereact-router

解决方案


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

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.
    // ...
  }
});


推荐阅读