【问题标题】:Unable to Persist Firebase Auth in a React Web Application无法在 React Web 应用程序中保留 Firebase Auth
【发布时间】:2023-02-03 01:09:09
【问题描述】:

我已经使用 Firebase Auth 在我的 React 网络应用程序中实现了注册和登录功能。

有一个登录页面:

登录后,我被重定向到 Home 页面,如下所示:

问题

Home 页面上,如果我刷新页面,我将注销并重定向到登录页面。我不想在页面刷新时注销。我希望授权持续存在。只有当我点击Logout 按钮时,我才应该注销。

我怎样才能做到这一点?

代码sn-ps如下:

登录.js

import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { updateDisplayName } from "./authSlice";
import { signInWithEmailAndPassword } from "firebase/auth";
import { auth } from "../firebase.config";
import { ReactComponent as ArrowRightIcon } from "../assets/svg/keyboardArrowRightIcon.svg";
import visibilityIcon from "../assets/svg/visibilityIcon.svg";

const Signin = () => {
  const [showPassword, setShowPassword] = useState(false);
  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });

  const { email, password } = formData;
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const handleChange = ({ target }) => {
    const { name, value } = target;
    setFormData({ ...formData, [name]: value });
  };

  const handleSignin = async (e) => {
    e.preventDefault();

    try {
       const auth = getAuth();
      const userCredential = await signInWithEmailAndPassword(
        auth,
        email,
        password
      );
      const user = userCredential.user;
      dispatch(updateDisplayName(user));
      navigate("/");
    } catch (error) {
      console.log(error.message);
    }
  };

  return (
    <>
      <div className="pageContainer">
        <header>
          <p className="pageHeader">Welcome Back!</p>
        </header>
        <main>
          <form onSubmit={handleSignin}>
            <input
              type="email"
              name="email"
              className="emailInput"
              placeholder="Email"
              value={email}
              onChange={handleChange}
            />
            <div className="passwordInputDiv">
              <input
                type={showPassword ? "text" : "password"}
                value={password}
                className="passwordInput"
                placeholder="password"
                name="password"
                onChange={handleChange}
              />
              <img
                src={visibilityIcon}
                alt="Show password"
                className="showPassword"
                onClick={() => setShowPassword(!showPassword)}
              />
              <Link to="/forgot-password" className="forgotPasswordLink">
                Forgot Password
              </Link>
              <div className="signInBar">
                <p className="signinText">Sign In</p>
                <button className="signInButton">
                  <ArrowRightIcon fill="#ffffff" width="34px" height="34px" />
                </button>
              </div>
            </div>
          </form>
          {/* Google OAuth */}
          <Link to="/sign-up" className="registerLink">
            Sign Up
          </Link>
        </main>
      </div>
    </>
  );
};
export default Signin;

首页.js

import React from "react";
import { useNavigate } from "react-router-dom";
import { getAuth, signOut } from "firebase/auth";
import { useSelector } from "react-redux";
import { selectDisplayName } from "./authSlice";

const Home = () => {
  const name = useSelector(selectDisplayName);

  const auth = getAuth();
  const navigate = useNavigate();

  const handleLogout = () => {
    signOut(auth);
    navigate("/sign-in");
  };

  return (
    <>
      <div>Wecome {name}</div>
      <button onClick={handleLogout}>Logout</button>
    </>
  );
};

export default Home;

firebase.config.js

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import {
  browserLocalPersistence,
  getAuth,
  setPersistence,
} from "firebase/auth";

const firebaseConfig = {
  // Details
};

const app = initializeApp(firebaseConfig);

export const db = getFirestore(app);

export const auth = getAuth(app);

setPersistence(auth, browserLocalPersistence);

【问题讨论】:

    标签: reactjs firebase firebase-authentication


    【解决方案1】:

    您必须使用onAuthStateChanged 来实现。我建议将该代码添加到App.js

    https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user

      import { auth } from "./firebase";
    
      const user = useSelector((state) => state.auth.user);
    
      // Check if user is logged in and set user data to persist state between page reloads
      useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged((user) => {
          dispatch(setUser(user));
        });
        return unsubscribe;
      }, [dispatch]);
    
     return (
      <Router>
        <Routes>
          <Route path="/" element={<Layout />}>
            <Route
              index
              element={user ? <Navigate to="locations" /> : <Auth />}
            />
           ...other routes...
    

    参考我的 GitHub 项目 - https://github.com/mile-mijatovic/React-CRUD-App/blob/master/src/App.js

    【讨论】:

    【解决方案2】:

    你解决这个问题了吗? 有同样的情况,用户在所有重新加载页面后注销,我用过:

      useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (user) => {
      await setPersistence(auth, browserLocalPersistence);
      
      setCurrentUser(user);
    });
    
    return unsubscribe;
    

    }, []);

    但是什么都没有改变。

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 2021-03-03
      • 2013-04-29
      • 1970-01-01
      • 2021-01-17
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      相关资源
      最近更新 更多