You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Firebase signInWithEmailAndPassword登录功能使用异常问题求助

Fixing Firebase Email/Password Login Issues in Your React Component

Let's break down what's going wrong and fix it step by step:

1. Core Problems in Your Current Code

  • You're not capturing form input: Right now, your form inputs have name attributes but no state bindings—so when a user types their email/password, those values aren't being saved or used in the login call. You're hardcoding "krishna@email.com" and "password" instead, which might not match a valid verified user in your Firebase project.
  • No error handling: Your signInWithEmailAndPassword call only has a .then() but no .catch(), so if login fails (invalid credentials, network issue, etc.), you won't see any error messages in the console, and your isLoading state will stay stuck as true.
  • Redundant auth initialization: You're importing getAuth in both Login.js and firebase.js—you can just use the pre-initialized auth from your firebase.js file to avoid any potential conflicts.

2. Step-by-Step Fixes

Update Login.js to Capture Form Inputs & Handle Errors

Here's the revised code with proper state binding, error handling, and cleaned-up auth usage:

import React, { useState } from 'react'
import { signInWithEmailAndPassword } from "firebase/auth";
import { auth } from './firebase'; // Import the pre-initialized auth from your config file

export default function Login() {
  const [isLoading, setIsLoading] = useState(false);
  const [email, setEmail] = useState(""); // State for email input
  const [password, setPassword] = useState(""); // State for password input
  const [error, setError] = useState(""); // State to show error messages

  function handleForm(e){
    e.preventDefault();
    setIsLoading(true);
    setError(""); // Clear previous errors

    // Use the captured email/password from state instead of hardcoded values
    signInWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        const user = userCredential.user;
        console.log("Logged in user:", user);
        // Add your post-login logic here (e.g., redirect to dashboard)
      })
      .catch((error) => {
        // Catch and display login errors
        setError(error.message);
        console.error("Login error:", error);
      })
      .finally(() => {
        // Reset loading state whether login succeeds or fails
        setIsLoading(false);
      });
  }

  return (
    <div className="flex h-screen bg-gray-200">
      <div className="m-auto w-1/3 text-white flex flex-wrap justify-center shadow-lg rounded-lg bg-gradient-to-br from-indigo-900 to-indigo-700">
        <form className="m-5 w-10/12" onSubmit={handleForm}>
          <h1 className="w-full text-4xl tracking-widest text-center my-6">
            Login
          </h1>
          {/* Display error message if exists */}
          {error && <div className="w-full text-red-300 text-center mb-4">{error}</div>}
          <div className="w-full my-6">
            <input 
              type="email" 
              className="p-2 rounded shadow w-full text-black" 
              placeholder="Email or Username" 
              value={email} // Bind input value to state
              onChange={(e) => setEmail(e.target.value)} // Update state on input change
              required
            />
          </div>
          <div className="w-full my-6">
            <input 
              type="password" 
              className="p-2 rounded shadow w-full text-black" 
              placeholder="Password" 
              value={password} // Bind input value to state
              onChange={(e) => setPassword(e.target.value)} // Update state on input change
              required
            />
          </div>
          <div className="w-full my-10">
            <button 
              type="submit" 
              className="p-2 rounded shadow w-full from-yellow-600 bg-yellow-400 text-black"
              disabled={isLoading} // Disable button while loading
            >
              {isLoading ? "Logging in..." : "Login"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

Verify Your firebase.js Configuration

Your existing firebase.js looks correct, but just double-check that:

  • You've enabled Email/Password sign-in in your Firebase Console (Authentication > Sign-in method)
  • The user krishna@email.com exists in your Firebase Authentication users list and has a verified email (if you enabled email verification requirement)

3. Additional Checks

  • Make sure you've installed the correct Firebase version (npm install firebase should pull the latest v9+ which matches your modular imports)
  • Clear your browser cache and restart your React dev server to ensure no old code is cached
  • Check your Firebase Console's Authentication logs for any failed login attempts (this can help debug issues like invalid credentials)

Once you make these changes, your login form should properly capture user input, handle success/error cases, and give you clear feedback in the console when something goes wrong.

内容的提问来源于stack exchange,提问作者rupapayal

火山引擎 最新活动