reactjs useState的问题

cfh9epnr  于 2022-12-29  发布在  React
关注(0)|答案(1)|浏览(135)

我知道我的代码在使用useState和useEffect方面是错误的,但我真的不知道我能做些什么来修复它。最终目标是每次我按下loginButton时,它都应该使用firebase身份验证并使用setUser函数将result.user的值存储到user中。我该如何修复这个问题呢?

import React, { useEffect, useState } from 'react'
import styled from 'styled-components'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faGoogle} from '@fortawesome/free-brands-svg-icons'
import { faHeart } from '@fortawesome/free-solid-svg-icons'
import { auth, provider, signInWithPopup, GoogleAuthProvider, onAuthStateChanged } from '../firebase'
import {useAuthState} from 'react-firebase-hooks/auth'

const Login = () => {

  const [user, setUser] = useState({})
  var tempUser = {}
  const [isLogged] = useAuthState(auth)
  const googleSignIn = async() =>{
    const result  = await signInWithPopup(auth, provider)
    tempUser = result.user
  }

  return (
        <div class="loginWrapper">
        <h1 className='title'>Monkey With The <br/> IMS.</h1>
        <button class="loginButton" onClick={()=>googleSignIn()} >Sign in With  <FontAwesomeIcon icon={faGoogle} /> </button>
        <p>Made with <FontAwesomeIcon icon={faHeart} style={{color: 'black'}} />, by Het Patel</p>
        </div>
  )
}

export default Login
jchrr9hc

jchrr9hc1#

您实际上并不需要额外的状态变量(user/setUser)。useAuthState钩子已经为您提供了一个状态变量 (在您的例子中名为isLogged,但在我的示例中我将其正确地重命名为user,每当auth状态发生变化时,该状态变量就会触发重新呈现,并在重新加载页面时保持该状态。
以下是一个简单的设置**(Firebase v9)**,可帮助您入门:

import { useAuthState } from 'react-firebase-hooks/auth';
import { initializeApp } from "firebase/app";
import { getAuth, signInWithPopup, GoogleAuthProvider, signOut } from "firebase/auth";
const firebaseConfig = {
  apiKey: "<API_KEY>",
  authDomain: "<...>",
  projectId: "<...>",
  storageBucket: "<...>",
  messagingSenderId: "<...>",
  appId: "<...>"
};
const firebaseApp = initializeApp(firebaseConfig);
const auth = getAuth(firebaseApp)
const provider = new GoogleAuthProvider();

function Child({ user }){
  return <p>{ user ? user.displayName + " Logged In" : "Logged Out" }</p>
}

export default function App(){

  const [user] = useAuthState(auth); // <= Everything you need is here. This acts as a state variable (triggers a render whenever the 'user' gets updated) therefore you don't need an extra 'user/setUser' state
  const googleSignIn = async() =>{
    await signInWithPopup(auth, provider); // When the process successfully signs the user in, the 'user' variable above will be updated automatically.
  }
  return (
        <>
          <h1>Monkey With The IMS.</h1>
          {/* You can use the 'user' variable to conditionally render content based on the auth state */}
          { user ? 
            <button onClick={()=>signOut(auth)}>Logout</button>
            :
            <button onClick={googleSignIn}>Sign in With Google</button>
          }
          {/* ...or you can pass the user object down the hierarchy tree or use the Context API for a more robust sharing strategy */}
          <Child user={user} />
        </>
  )
};

根据您的设置和用例,您可能希望考虑使用ContextAPI或通过Redux、Zustand等状态管理库共享auth状态。

  • 参考资料:*

React-火线-挂钩/授权

相关问题