如何使用带有钩子的本地状态实施Firebase身份验证?

时间:2020-02-26 19:10:00

标签: javascript reactjs firebase firebase-authentication

我一直遵循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>
  );
}

1 个答案:

答案 0 :(得分:1)

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

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

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

要制作适当的钩子,请像这样设置Login

useEffect