import React, { useRef, useState } from "react"
import { Form, Button, Card, Alert } from "react-bootstrap"
import { useAuth } from "../contexts/AuthContext"
import { Link, useNavigate} from "react-router-dom"

export default function Signup() {
  const emailRef = useRef()
  const passwordRef = useRef()
  const passwordConfirmRef = useRef()
  const { signup } = useAuth()
  const [error, setError] = useState("")
  const [loading, setLoading] = useState(false)
  const history = useNavigate()

  async function handleSubmit(e) {
    e.preventDefault()

    if (passwordRef.current.value !== passwordConfirmRef.current.value) {
      return setError("Passwords do not match")
    }

    try {
      setError("")
      setLoading(true)
      await signup(emailRef.current.value, passwordRef.current.value)
      history.push("/")
    } catch {
      setError("Failed to create an account")
    }

    setLoading(false)
  }

  return (
    <>
      <Card>
        <Card.Body>
          <h2 className="text-center mb-4">Sign Up</h2>
          {error && <Alert variant="danger">{error}</Alert>}
          <Form onSubmit={handleSubmit}>
            <Form.Group id="email">
              <Form.Label>Email</Form.Label>
              <Form.Control type="email" ref={emailRef} required />
            </Form.Group>
            <Form.Group id="password">
              <Form.Label>Password</Form.Label>
              <Form.Control type="password" ref={passwordRef} required />
            </Form.Group>
            <Form.Group id="password-confirm">
              <Form.Label>Password Confirmation</Form.Label>
              <Form.Control type="password" ref={passwordConfirmRef} required />
            </Form.Group>
            <Button disabled={loading} className="w-100" type="submit">
              Sign Up
            </Button>
          </Form>
        </Card.Body>
      </Card>
      <div className="w-100 text-center mt-2">
        Already have an account? <Link to="/login">Log In</Link>
      </div>
    </>
  )
}

我正在try 创建一个与我的Firebase.js文件相连接的注册页面,但每当我try 创建用户时,它总是抛出一个错误"无法创建帐户".

我试过的是:

  • 已更改身份验证密钥
  • 在Firebase的用户中再次删除或添加本地主机
  • 问题仍然存在
import React, { useContext, useState, useEffect } from "react"
import { auth } from "../firebase"

const AuthContext = React.createContext()

export function useAuth() {
    return useContext(AuthContext)
  }

export function AuthProvider({ children }) { 
    const [currentUser, setCurrentUser] = useState()
    const [loading, setLoading] = useState(true)


    function signup(email, password) {
        return auth.createUserWithEmailAndPassword(email, password)
    }


    useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(user => {
            setCurrentUser(user)
            setLoading(false)
        })

        return unsubscribe
    }, [])

    const value = {
        currentUser,
        // login,
        signup,
        // logout,
        // resetPassword,
        // updateEmail,
        // updatePassword
      }
    

    return (
        <AuthContext.Provider value={value}>
            {!loading && children}
        </AuthContext.Provider>
    )

}

这是我的AuthConext.js文件,但仍然不确定.

下面是我的Firebase.js文件.

import "firebase/auth"
import { initializeApp } from "firebase/app";

import { getAuth } from "firebase/auth";


const app = initializeApp({
    apiKey: 
    authDomain: ,
    projectId: ,
    storageBucket: ,
    messagingSenderId:,
    appId: 
})


export const auth = getAuth(app);
export default app

我已经删除了creds,所以我仍然不确定的问题

推荐答案

下面是一个用于向Firebase注册新用户的工作函数.(我将其放在一个定制钩子中,我在注册页面上将其称为钩子).

首先,初始化Firebase(为清楚起见,我添加了以下代码,但建议将其与Firebase配置文件一起存储,并将其导入到自定义挂钩中)

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);

函数来创建新用户.提交时只需从表单中传递一个包含邮箱、密码等的对象即可.

const signUpWithEmailAndPassword = (formData) => {
        const { email, password, displayName } = formData;
        createUserWithEmailAndPassword(auth, email, password, displayName)
            .then((userCredential) => {
                // Signed in
                const user = userCredential?.user;
                const uid = userCredential?.user?.uid;
                    loginService(uid, user); //this is where you would dispatch your login service which can be reused with your other sign-in options (Google/Facebook/etc)
            })
            .catch((error) => {
                alert(error.message);
                console.log(
                    'Error Signing Up with Email & Password. Error Message: ',
                    error.message
                );
            });
    };

我也同意Drew的观点,虽然所提供的信息不足以调试您的代码,但问题似乎出在您的环境中.我建议您try 使用上面的函数创建一个新用户,并只记录结果,如果它有效,则可以开始调试您的上下文.

祝好运!

Reactjs相关问答推荐

react-native-markdown-显示样式表

如何使用React防止并发注册并处理Firestore数据库中的插槽可用性

为什么安装FLOBIT后,所有的输入FIELD现在都有一个蓝色的轮廓?

在Reaction中管理多个状态

如何使用TouchStart/TouchEnd在Table ReactJS中交换位置?

shadcn输入+窗体+Zod;一个部件正在改变要被控制的不受控制的输入;

.populate() 方法在 mongodb 中不起作用

警告:遇到两个子元素拥有同一把 keys .键应该是唯一的,以便组件在更新时保持其身份

react 本机屏幕转换

React useContext 的未定义返回值

Next.js i18n 路由不适用于动态路由

单元测试 useLoaderData() react-router v6 加载器函数

使用 React.lazy 调试 webpack 代码拆分

vdom 最终更新了 dom(在比较之后)任何 dom 更改实际上应该触发整个树的重绘和回流,那么 vdom 有什么用?

如何制作基于对象 struct 呈现数据的可重用组件?

需要帮助在 document.queryselector 的 nextjs 页面上插入 useEffect 状态

如何在 JSX 中使用 -webkit- 前缀?

如何跨微前端 React 应用管理状态管理?

react 路由dom没有路由匹配位置错误/在路由中制作组件

在react 路由dom版本6中的组件内添加路由