如何在我的 React 应用程序中强制使用 Firebase 身份验证进行注册? [英] How to make registration mandatory with Firebase auth in my React app?

查看:28
本文介绍了如何在我的 React 应用程序中强制使用 Firebase 身份验证进行注册?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑以添加详细信息

应用程序必须从一个带有表单的页面开始,输入电子邮件和密码,当登录将我们带到菜单屏幕时,我在屏幕截图中显示.但是,当我输入电子邮件和密码时,应用程序不会移动.日志有效,因为 consolelog() 向我展示了它

这是第二张截图

我不明白我做错了什么.现在我显示修改后的App.js文件来显示表单,但是当我注册时,应用程序没有到达Menu,页面<Sidebar/>

archivo App.js modificado

import React, { useState, useEffect } from 'react'从反应路由器"导入 { Routes, Route }导入 firebase, { FirebaseContext } from './firebase'//从'firebase'导入{ auth }从'./firebase' 导入 firebaseObj从'./components/paginas/Ordenes'导入Ordenes从'./components/paginas/Menu'导入菜单从 './components/paginas/NuevoPlato' 导入 NuevoPlato从'./components/ui/Sidebar'导入侧边栏从'./components/Signin'导入登录const auth = firebaseObj.auth功能应用(){const [user, setUser] = useState(null)useEffect(() => {const unsubscribe = auth.onAuthStateChanged(userAuth => {常量用户 = {uid: userAuth?.uid,电子邮件:userAuth?.email}如果(用户身份验证){控制台日志(用户身份验证)设置用户(用户)} 别的 {设置用户(空)}})返回退订}, [])返回 (<FirebaseContext.Provider价值={{火力基地}}><div className="md:flex min-h-screen";><div className="md:w-2/5 xl:w-4/5 p-6"><路线><路由路径="/";element={<登录/>}/><路由路径="/sidebar";element={<侧边栏/>}/><Route path="/ordenes";element={<Ordenes/>}/><路由路径=/menu";element={<Menu/>}/><Route path="/nuevo-plato";element={<NuevoPlato/>}/></路线>

</FirebaseContext.Provider>)}导出默认应用

我用 React 创建了一个 Web 应用程序(https://github.com/facebook/create-react-app. --- npx create-react-app my-app)

这是一个简单的应用程序,具有三个屏幕:主屏幕、菜单、新产品显示商店产品列表的应用程序,用户可以从中添加更多产品.完成后,我决定必须通过电子邮件注册才能查看内容并能够添加产品.我已经添加了适当的配置来通过 Firebase 登录,应用程序总是直接启动,尽管它显示了注册表.

App.js 的配置是正确的,但是我不知道如何让我的应用程序从Signin 启动,并且一旦输入电子邮件和用户名,我就被发送到应用程序

我尝试了几种方法,在所有方法中都是直接启动应用程序.我已经在App.js中添加了Signin,但是需要看App.js显示的内容,需要输入邮箱和密码.现在,有应用程序菜单

文件 App.js

import React, { useState, useEffect } from 'react'从反应路由器"导入 { Routes, Route }导入 firebase, { FirebaseContext } from './firebase'//从'firebase'导入{ auth }从'./firebase' 导入 firebaseObj从'./components/paginas/Ordenes'导入Ordenes从'./components/paginas/Menu'导入菜单从 './components/paginas/NuevoPlato' 导入 NuevoPlato从'./components/ui/Sidebar'导入侧边栏从'./components/Signin'导入登录const auth = firebaseObj.auth功能应用(){const [user, setUser] = useState(null)useEffect(() => {const unsubscribe = auth.onAuthStateChanged(userAuth => {常量用户 = {uid: userAuth?.uid,电子邮件:userAuth?.email}如果(用户身份验证){控制台日志(用户身份验证)设置用户(用户)} 别的 {设置用户(空)}})返回退订}, [])返回 (<FirebaseContext.Provider价值={{火力基地}}><div className="md:flex min-h-screen";><侧边栏/><div className="md:w-2/5 xl:w-4/5 p-6"><路线><路由路径="/";element={<Ordenes/>}/><路由路径=/menu";element={<Menu/>}/><Route path="/nuevo-producto";element={<NuevoProducto/>}/></路线>

</FirebaseContext.Provider>)}导出默认应用

文件 Signin.js

import React, { useRef } from 'react'//从 '../firebase' 导入 { auth }从'../firebase/firebase' 导入 firebaseObjconst auth = firebaseObj.authconst Signin = () =>{const emailRef = useRef(null);const passwordRef = useRef(null);const signUp = e =>{e.preventDefault();auth.createUserWithEmailAndPassword(emailRef.current.value,密码Ref.current.value).then(用户 => {控制台日志(用户)}).catch(err => {控制台日志(错误)})}const signIn = e =>{e.preventDefault();auth.signInWithEmailAndPassword(emailRef.current.value,密码Ref.current.value).then(用户 => {控制台日志(用户)}).catch(err => {控制台日志(错误)})}返回 (<div className="mb-4"><form action=""><h1>登录</h1><输入className =阴影外观-无边框圆形 w-full py-2 px-3 text-gray-700 前导紧焦点:轮廓-无焦点:阴影轮廓"ref={emailRef} type=电子邮件"占位符=电子邮件"/><输入className =阴影外观-无边框圆形 w-full py-2 px-3 text-gray-700 前导紧焦点:轮廓-无焦点:阴影轮廓"ref={passwordRef} type=密码"/><button onClick={signIn}>登录</button></表单>

)}导出默认登录

解决方案

注册后没有进入SignIn页面的原因是没有逻辑.如果你只是一个简单的 if statament 像这里它应该工作:

import React, { useState, useEffect } from "react";从反应路由器"导入{路线,路线};import firebase, { FirebaseContext } from "./firebase";//从'firebase'导入{ auth }从./firebase"导入 firebaseObj;从./components/paginas/Ordenes"导入Ordenes;从./components/paginas/Menu"导入菜单;从./components/paginas/NuevoPlato"导入 NuevoPlato;从./components/ui/Sidebar"导入侧边栏;从./components/Signin"导入登录;const auth = firebaseObj.auth;功能应用(){const [user, setUser] = useState(null);useEffect(() => {const unsubscribe = auth.onAuthStateChanged((userAuth) => {常量用户 = {uid: userAuth?.uid,电子邮件:userAuth?.email,};如果(用户身份验证){控制台日志(用户身份验证);设置用户(用户);} 别的 {设置用户(空);}});返回退订;}, []);如果(!用户){返回 (<div className="md:flex min-h-screen"><div className="md:w-2/5 xl:w-4/5 p-6"><登录/>

);} 别的 {返回 (<FirebaseContext.Provider价值={{火力基地,}}><div className="md:flex min-h-screen"><div className="md:w-2/5 xl:w-4/5 p-6"><路线><路由路径="/";element={<侧边栏/>}/><路由路径="/sidebar";element={<侧边栏/>}/><Route path="/ordenes";element={<Ordenes/>}/><路由路径=/menu";element={<Menu/>}/><Route path="/nuevo-plato";element={<NuevoPlato/>}/></路线>

</FirebaseContext.Provider>);}}导出默认应用程序;

这只是为了举例.我建议将 auth 状态侦听器放入 Provider 并创建自定义路由,如果没有用户登录,这些路由会自动重新路由到 SignIn 页面.

这里 你有一个这样的 Provider 的例子,我在我的每个项目中都使用了它.

这里 是那些正在侦听该提供者的自定义路由的示例.

EDIT TO ADD DETAILS

The application must be started with a page with a form, enter email and password and when Login takes us to the menu screen, which I show in the screenshot. However, when I enter the email and password, the application does not move. The log works, because a consolelog() shows it to me

It's the second screenshot

I do not understand what I have wrong. Now I show the modified App.js file to show the form, but when I register, the application does not reach the Menu, page <Sidebar />

archivo App.js modificado

import React, { useState, useEffect } from 'react'
import { Routes, Route } from 'react-router'

import firebase, { FirebaseContext } from './firebase'
//import { auth } from 'firebase' 
import firebaseObj from './firebase'
import Ordenes from './components/paginas/Ordenes'
import Menu from './components/paginas/Menu'
import NuevoPlato from './components/paginas/NuevoPlato'
import Sidebar from './components/ui/Sidebar'
import Signin from './components/Signin'

const auth = firebaseObj.auth

function App() {

  const [user, setUser] = useState(null)
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(userAuth => {
      const user = {
        uid: userAuth?.uid,
        email: userAuth?.email
      }
      if (userAuth) {
        console.log(userAuth)
        setUser(user)
      } else {
        setUser(null)
      }
    })
    return unsubscribe
  }, [])

  return (
    <FirebaseContext.Provider
      value={{
        firebase
      }}
    >
      <div className="md:flex min-h-screen" >
        <div className="md:w-2/5 xl:w-4/5 p-6">
          <Routes>
            <Route path="/" element={<Signin />} />
            <Route path="/sidebar" element={<Sidebar />} />
            <Route path="/ordenes" element={<Ordenes />} />
            <Route path="/menu" element={<Menu />} />
            <Route path="/nuevo-plato" element={<NuevoPlato />} />
          </Routes>
        </div>
      </div>

    </FirebaseContext.Provider>
  )
}

export default App

I have created a web application with React (https://github.com/facebook/create-react-app. --- npx create-react-app my-app)

It is a simple application with three screens: Main, Menu, New Products The App that shows a list of products from a store, from where the user can add more products. Once finished, I have decided that registration by email is mandatory in order to see the content and be able to add products. I have added the appropriate configuration to get the login through Firebase, the application always starts directly, although it shows the registration form.

The configuration of App.js is correct, but I don't know how to make my application start from Signin, and once the email and user name were entered, I was sent to the application

I have tried several ways, and in all of them it starts the application directly. I have added Signin to App.js, but I need to see what App.js shows, it is necessary to enter the email and password. Now, there is the application menu

File App.js

import React, { useState, useEffect } from 'react'
import { Routes, Route } from 'react-router'

import firebase, { FirebaseContext } from './firebase'
//import { auth } from 'firebase' 
import firebaseObj from './firebase'
import Ordenes from './components/paginas/Ordenes'
import Menu from './components/paginas/Menu'
import NuevoPlato from './components/paginas/NuevoPlato'
import Sidebar from './components/ui/Sidebar'
import Signin from './components/Signin'

const auth = firebaseObj.auth

function App() {

  const [user, setUser] = useState(null)
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(userAuth => {
      const user = {
        uid: userAuth?.uid,
        email: userAuth?.email
      }
      if (userAuth) {
        console.log(userAuth)
        setUser(user)
      } else {
        setUser(null)
      }
    })
    return unsubscribe
  }, [])

  return (
    <FirebaseContext.Provider
      value={{
        firebase
      }}
    >
      <div className="md:flex min-h-screen" >
        <Sidebar />

        <div className="md:w-2/5 xl:w-4/5 p-6">
          <Routes>
            <Route path="/" element={<Ordenes />} />
            <Route path="/menu" element={<Menu />} />
            <Route path="/nuevo-producto" element={<NuevoProducto />} />
          </Routes>

        </div>

      </div>

    </FirebaseContext.Provider>
  )
}

export default App

File Signin.js

import React, { useRef } from 'react'
//import { auth } from '../firebase'
import firebaseObj from '../firebase/firebase'

const auth = firebaseObj.auth

const Signin = () => {
    const emailRef = useRef(null);
    const passwordRef = useRef(null);
    const signUp = e => {
        e.preventDefault();
        auth.createUserWithEmailAndPassword(
            emailRef.current.value,
            passwordRef.current.value
        ).then(user => {
            console.log(user)
        }).catch(err => {
            console.log(err)
        })
    }
    const signIn = e => {
        e.preventDefault();
        auth.signInWithEmailAndPassword(
            emailRef.current.value,
            passwordRef.current.value
        ).then(user => {
            console.log(user)
        }).catch(err => {
            console.log(err)
        })
    }
    return (
        <div className="mb-4">
            <form action="">
                <h1>Sign in</h1>
                <input
                className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                ref={emailRef} type="email" placeholder="email"/>
                <input 
                className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                ref={passwordRef} type="password" />
                <button onClick={signIn}>Sign in </button>
            </form>
        </div>
    )
}

export default Signin

解决方案

The reason you don't get to the SignIn page after you register is that there is no logic for it. If you make just a simple if statament like here it should work:

import React, { useState, useEffect } from "react";
import { Routes, Route } from "react-router";

import firebase, { FirebaseContext } from "./firebase";
//import { auth } from 'firebase'
import firebaseObj from "./firebase";
import Ordenes from "./components/paginas/Ordenes";
import Menu from "./components/paginas/Menu";
import NuevoPlato from "./components/paginas/NuevoPlato";
import Sidebar from "./components/ui/Sidebar";
import Signin from "./components/Signin";

const auth = firebaseObj.auth;

function App() {
  const [user, setUser] = useState(null);
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((userAuth) => {
      const user = {
        uid: userAuth?.uid,
        email: userAuth?.email,
      };
      if (userAuth) {
        console.log(userAuth);
        setUser(user);
      } else {
        setUser(null);
      }
    });
    return unsubscribe;
  }, []);

  if (!user) {
    return (
      <div className="md:flex min-h-screen">
        <div className="md:w-2/5 xl:w-4/5 p-6">
          <Signin />
        </div>
      </div>
    );
  } else {
    return (
      <FirebaseContext.Provider
        value={{
          firebase,
        }}
      >
        <div className="md:flex min-h-screen">
          <div className="md:w-2/5 xl:w-4/5 p-6">
            <Routes>
              <Route path="/" element={<Sidebar />} />
              <Route path="/sidebar" element={<Sidebar />} />
              <Route path="/ordenes" element={<Ordenes />} />
              <Route path="/menu" element={<Menu />} />
              <Route path="/nuevo-plato" element={<NuevoPlato />} />
            </Routes>
          </div>
        </div>
      </FirebaseContext.Provider>
    );
  }
}

export default App;

That is just for example purpose. I would recommend to put the auth state listener into a Provider and create custom routes that automaticaly reroute to the SignIn page if no user is logged in.

Here you have an example of such an Provider that I use in every of my projects.

An here is an example of those custom routes that are listening to that provier.

这篇关于如何在我的 React 应用程序中强制使用 Firebase 身份验证进行注册?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆