【问题标题】:How do I implement Firebase authentication with local state with hooks?如何使用带有钩子的本地状态实现 Firebase 身份验证?
【发布时间】:2020-02-26 19:10:00
【问题描述】:

我正在关注using-firebaseauth-with-local-state 在我的 React 应用程序中实现身份验证,但我正在使用功能组件和挂钩。我应该如何实现componentDidMount()componentWillUnmount()

这是我在Login.jsx 组件中的代码:

import React, { useState, useEffect } from 'react'

import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";
import firebase from "firebase";


// Configure Firebase.
const config = {
  apiKey: "myapikey",
  authDomain: "mydomain.firebaseapp.com"
  // ...
};
firebase.initializeApp(config);

// Configure FirebaseUI.
const uiConfig = {
  // Popup signin flow rather than redirect flow.
  signInFlow: "popup",
  // Redirect to /signedIn after sign in is successful. Alternatively you can provide a callbacks.signInSuccess function.
  signInSuccessUrl: "/",
  // We will display Google and Facebook as auth providers.
  signInOptions: [
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    firebase.auth.FacebookAuthProvider.PROVIDER_ID
  ],
  callbacks: {
    // Avoid redirects after sign-in.
    signInSuccessWithAuthResult: () => false
  }
};

export default function Login() {
  const [signedIn, setSignIn]= useState(false);

  useEffect(() => {
    return () => {
    const unregisterAuthObserver = firebase.auth().onAuthStateChanged(
        (user) => setSignIn({isSignedIn: !!user})
    );
    unregisterAuthObserver();
    console.log("Sdd")
    };
  })

  if (!signedIn) {
    return (
      <div>
        <h1>My App</h1>
        <p>Please sign-in:</p>
        <StyledFirebaseAuth
          uiConfig={uiConfig}
          firebaseAuth={firebase.auth()}
        />
      </div>
    );
  }

  return (
    <div>
      <h1>My App</h1>
      <p>Welcome {firebase.auth().currentUser.displayName}! You are now signed-in!</p>
      <a onClick={() => firebase.auth().signOut()}>Sign-out</a>
    </div>
  );
}

【问题讨论】:

  • 你检查我的答案了吗?如果您有任何疑虑或它对您不起作用,请告诉我。如果您发现答案有用,请考虑接受它。请阅读What should I do when someone answers my question?
  • 我还没试过。但我现在要这样做

标签: javascript reactjs firebase firebase-authentication


【解决方案1】:

我应该如何实现componentDidMount()componentWillUnmount()?

使用useEffect 和一个空数组来模拟componentDidMount;然后从同一个useEffect 返回一个函数来模拟componentWillUnmount

在您的代码中,useEffect 返回一个函数,这意味着该函数将在组件卸载时执行,因此当您完成 Login 组件时,您的 firebase.auth().onAuthStateChanged 将被挂钩。

要制作正确的钩子,请像这样设置useEffect

useEffect(() => {

  const unregisterAuthObserver = firebase.auth()
    .onAuthStateChanged(
      (user) => setSignIn({isSignedIn: !!user})
    );

  // Now you either return just unregisterAuthObserver
  // which will be called when the component is unmounted
  return unregisterAuthObserver;

  // or you create a function if you want more login when the component is unmounted
  // return () => {
  //   unregisterAuthObserver();
  //   console.log("Sdd");
  // }

}, []); // Important, pass an empty array so to execute useEffect hook only once

【讨论】:

    猜你喜欢
    • 2017-12-29
    • 2017-11-29
    • 1970-01-01
    • 2019-03-25
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    相关资源
    最近更新 更多