繁体   English   中英

useState 问题

[英]Issue with useState

我知道我的代码在使用 useState 和 useEffect 方面是错误的,但我真的不明白我能做些什么来修复它。 最终目标是每次我按下登录按钮时,它应该使用 firebase 身份验证并使用 setUser function 将 result.user 的值存储到用户中。 我将如何解决此问题 go。

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

你真的不需要额外的 state 变量( user/setUser )。 useAuthState挂钩已经为您提供了一个 state 变量(在您的案例中名为isLogged ,但在我的示例中我将其正确重命名为user触发重新渲染,只要 auth state 更改并在重新加载页面时保留 auth state。

这是一个简单的设置(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} />
        </>
  )
};

根据您的设置和用例,您可能需要考虑使用上下文 API 或通过 state 管理库(如 Redux、Zustand 等)共享身份验证 state。

参考:

反应-firebase-hooks/auth

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM