Reactjs 如何检查用户是否在react中使用firebase进行身份验证

Reactjs 如何检查用户是否在react中使用firebase进行身份验证,reactjs,firebase,react-native,react-router,Reactjs,Firebase,React Native,React Router,我在react项目中有多个页面,包括signin.js和signup.js。 在我的登录页面中,我可以登录并查看用户详细信息。但是,当我切换到注册页面时,我无法在此代码中使用{user}。 我也想在注册页面中查看登录的用户详细信息。谁能帮我猜个谜吗。 我是新手 signin.js 从“React”导入React 从“firebase/app”导入*作为firebase; 导入“firebase/auth”; 导出默认类注册扩展React.Component{ 状态={ 电子邮件:“”, 密码:

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

我也想在注册页面中查看登录的用户详细信息。谁能帮我猜个谜吗。 我是新手

signin.js
从“React”导入React
从“firebase/app”导入*作为firebase;
导入“firebase/auth”;
导出默认类注册扩展React.Component{
状态={
电子邮件:“”,
密码:“”,
名字:'',
姓氏:“”
}
handleChange=(e)=>{
这是我的国家({
[e.target.id]:e.target.value
})
}
handleSubmit=(e)=>{
e、 预防默认值()
console.log(this.state)
firebase.auth().createUserWithEmailAndPassword(this.state.email,this.state.password)。然后((用户)=>{
console.log(user)}).catch(函数(错误){
警报(“错误:”+错误消息);
})
}
render(){
返回(
报名
名字
姓
电子邮件
密码
报名
)
}
}

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

firebase.auth().onAuthStateChanged(函数(用户){
如果(用户){
//用户已登录。
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;
// ...
}否则{
//用户已注销。
// ...
}

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

firebase.auth().onAuthStateChanged(函数(用户){
如果(用户){
//用户已登录。
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;
// ...
}否则{
//用户已注销。
// ...
}

});首次呈现组件后,componentDidMount将运行。如果用户已登录,onAuthStateChanged函数将有权访问包含用户信息的{user}。然后,您可以通过这个.setState({email:user.email})将此信息保存到组件状态

类签名扩展了React.Component{
状态={
电子邮件:“”,
密码:“”
}
componentDidMount(){
firebase.auth().onAuthStateChanged(函数(用户){
如果(用户){
console.log(用户)
this.setState({email:user.email})
}
}
handleChange=(e)=>{
这是我的国家({
[e.target.id]:e.target.value
})

}
组件首次呈现后,componentDidMount将运行。如果用户已登录,onAuthStateChanged函数将访问包含用户信息的{user}。然后,您可以通过此.setState({email:user.email})将此信息保存到组件状态

类签名扩展了React.Component{
状态={
电子邮件:“”,
密码:“”
}
componentDidMount(){
firebase.auth().onAuthStateChanged(函数(用户){
如果(用户){
console.log(用户)
this.setState({email:user.email})
}
}
handleChange=(e)=>{
这是我的国家({
[e.target.id]:e.target.value
})

}
登录后,您可以将数据保存在本地存储中,并且可以在您的计算机中的任何位置访问本地存储project@AmitRai您好,谢谢。我是react js新手。我可以使用状态或任何其他东西来执行此操作吗?请指定它。登录后,您可以将数据保存在本地存储中,并且可以访问您计算机中任何位置的本地存储project@AmitRai你好,谢谢。我是react js新手。我可以使用state或其他任何东西来做吗?请指定它好吗?它不起作用。请解释一下,或者我如何使用componentDidmount()好吗?componentDidMount是React类的生命周期方法。基本上,在您的组件第一次呈现后,它只会执行一段代码。请检查我的另一个答案中的编码示例。它不起作用。请您解释一下,或者我如何使用componentDidMount()?componentDidMount是React类的生命周期方法。基本上,它只执行一段代码一次,
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>
        )
    }
}