Firebase sendPasswordResetEmail 在 React 中不起作用

Firebase sendPasswordResetEmail not working in React

我尝试使用 firebase 为网络应用程序创建密码重置选项,其他 firebase 选项工作正常,如 GoogleLogin 和电子邮件注册,但是当我尝试 sendPasswordResetEmail 它 returns 后出现错误,

TypeError: firebase__WEBPACK_IMPORTED_MODULE_1_.auth.sendPasswordResetEmail is not a function

这是代码, firebase.js

import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider, signInWithPopup } from "firebase/auth";

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID
};

const app = initializeApp(firebaseConfig);

export const auth = getAuth(app);
export const provider = new GoogleAuthProvider();
export const signInWithGooglePopUp = signInWithPopup

export default app;

AuthContext.js

import React, { useContext, useState, useEffect } from "react"
import { auth, provider, signInWithGooglePopUp } 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)
  }

  function login(email, password) {
    return auth.signInWithEmailAndPassword(email, password)
  }

  function logout() {
    return auth.signOut()
  }

  function resetPassword(email) {
    alert('')
    return auth.sendPasswordResetEmail(email).then((a) => {
      alert(a)
    })
  }

  function updateEmail(email) {
    return currentUser.updateEmail(email)
  }

  function updatePassword(password) {
    return currentUser.updatePassword(password)
  }

  function signupWithGoogle() {
    return signInWithGooglePopUp(auth, provider).then((result) => {
      console.log(result)
    }).catch((error) => {
      console.log(error)
    })
  }

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

    return unsubscribe
  }, [])

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

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

ForgotPassword.js

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

export default function ForgotPassword() {
    const emailRef = useRef()
    const { resetPassword } = useAuth()
    const [error, setError] = useState("")
    const [message, setMessage] = useState("")
    const [loading, setLoading] = useState(false)

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

        try {
            setMessage("")
            setError("")
            setLoading(true)
            console.log('wait')
            await resetPassword(emailRef.current.value)
            console.log('done')
            setMessage("Check your inbox for further instructions")
        } catch (error) {
            console.log(error)
            setError("Failed to reset password")
        }

        setLoading(false)
    }

    return (
        <>
            <Card>
                <Card.Body>
                    <h2 className="text-center mb-4">Password Reset</h2>
                    {error && <Alert variant="danger">{error}</Alert>}
                    {message && <Alert variant="success">{message}</Alert>}
                    <Form onSubmit={handleSubmit}>
                        <Form.Group id="email">
                            <Form.Label>Email</Form.Label>
                            <Form.Control type="email" ref={emailRef} required />
                        </Form.Group>
                        <Button disabled={loading} className="w-100" type="submit">
                            Reset Password
                        </Button>
                    </Form>
                    <div className="w-100 text-center mt-3">
                        <Link to="/login">Login</Link>
                    </div>
                </Card.Body>
            </Card>
            <div className="w-100 text-center mt-2">
                Need an account? <Link to="/signup">Sign Up</Link>
            </div>
        </>
    )
}

这里有什么问题,在此先感谢。

您正在使用 Firebase Modular SDK (V9.0.0+),其中 sendPasswordResetEmail 是一个函数,而不是 Auth 实例上的一个方法。所以应该是:

import { sendPasswordResetEmail } from "firebase/auth"
import { auth } from "../firebase"

function resetPassword(email) {
  return sendPasswordResetEmail(auth, email).then((a) => {
    alert("Password reset email sent")
  })
}

这同样适用于其他功能,如 createUserWithEmailAndPassword()signOut() 等。我不确定为什么错误只出现在这个功能上。

请查看 Firebase Auth 的 documentation 以了解有关这些功能的更多信息。