簡體   English   中英

為什么我的反應 state 沒有正確改變?

[英]Why is my react state not changing properly?

我正在嘗試使用 firebase 進行身份驗證。 這是跟蹤我的身份驗證 state 的組件。

    import { useState} from "react";


    function useAuth(fbAuth) {
       const [isAuthenticated, setIsAuthenticated] = useState(false);
       const createEmailUser = (email, password) => fbAuth.createUserWithEmailAndPassword(email, password);
       const signInEmailUser  = (email, password) => fbAuth.signInWithEmailAndPassword(email, password);
       const signOut = fbAuth.signOut();

       fbAuth.onAuthStateChanged(async user=> {
          if (user) {
             await setIsAuthenticated(true);
             console.log(isAuthenticated, "should be true")
             return
          } else {
             await setIsAuthenticated(false);
             console.log(isAuthenticated, "should be false")
             return
          }

        });

       return {isAuthenticated, createEmailUser, signInEmailUser, signOut};

    }

    export default useAuth

我單擊登錄時的控制台日志是

2useAuth.js:13 false “應該是真的”

2useAuth.js:17 假“應該是假的”

2useAuth.js:17 真“應該是假的”

4useAuth.js:17 假“應該是假的”

setIsAuthenticated function 不返回 promise,所以在這里使用await並沒有真正做任何事情。 最重要的是,永遠不會修改isAuthenticated的值(調用setIsAuthenticated不會更改您在掛鈎開始時已經設置的變量的值)。 基本上,在onAuthStateChanged function 中執行console.log沒有任何意義,也不會達到您的預期。 如果您想更好地了解正在發生的事情,請嘗試將console.log放在 function 的開頭,然后打印您希望它會改變的事實。 所以是這樣的:

import { useState, useEffect } from "react";

function useAuth(fbAuth) {
   const [isAuthenticated, setIsAuthenticated] = useState(false);
   const createEmailUser = (email, password) => fbAuth.createUserWithEmailAndPassword(email, password);
   const signInEmailUser  = (email, password) => fbAuth.signInWithEmailAndPassword(email, password);
   const signOut = fbAuth.signOut();

   console.log('isAuthenticated', isAuthenticated)
   //I'm assuming you only need to register the fbAuth.onAuthStateChanged
   //callback once. So We use useEffect with an empty array to have it
   //only run the first time this is rendered.
   useEffect(() => {
       fbAuth.onAuthStateChanged(async user=> {
          if (user) {
             setIsAuthenticated(true);
             console.log('isAuthenticated should be true after this')
          } else {
             setIsAuthenticated(false);
             console.log('isAuthenticated should be false after this')
          }
        });
    }, [])

    return {isAuthenticated, createEmailUser, signInEmailUser, signOut};

}

export default useAuth

然后你會期望

//Initial render
isAuthenticated false

//Click log-in
isAuthenticated should be true after this
isAuthenticated true

//Click log-out
isAuthenticated should be false after this
isAuthenticated false

我覺得這里沒有錯。 您是在更改之前獲取值。 要訪問最新的 state,您可以使用useEffect掛鈎。 你也沒有問過你的問題是什么,你期望什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM