gpt4 book ai didi

javascript - 如何通过钩子(Hook)实现具有本地状态的 Firebase 身份验证?

转载 作者:行者123 更新时间:2023-12-02 21:38:52 25 4
gpt4 key购买 nike

我正在关注using-firebaseauth-with-local-state在我的 react 应用程序中实现身份验证,但我正在使用功能组件和 Hook 。我应该如何实现 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>
);
}

最佳答案

How am I supposed to implement the componentDidMount() and componentWillUnmount()?

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

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

要制作适当的钩子(Hook),请像这样设置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

关于javascript - 如何通过钩子(Hook)实现具有本地状态的 Firebase 身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60420906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com