【问题标题】:Redux firebase - Handle authenticated state properly (first few miliseconds state is null until loaded)Redux firebase - 正确处理身份验证状态(前几毫秒状态为空,直到加载)
【发布时间】:2022-01-15 07:22:17
【问题描述】:

我在我的 React 应用程序中使用带有 redux 的 firebase,在这里遇到了一些问题。第一个是:

  1. 首次应用启动后,使用电子邮件/密码登录或通过社交(google、fb、apple)登录不会检测到已验证状态(标题内容取决于已验证/未验证状态),直到页面刷新。每次下一次登录时,登录/注销后标题内容都会发生变化,并且会检测到状态变化。解决方法是在await firebase.auth().signInWithEmailAndPassword(email, password); 之后添加window.location.reload(),但我不希望这种额外的重新加载。

  2. 当身份验证状态为 null 时,初始的几毫秒时间,即使用户在应用启动或应用刷新时登录 firebase,直到填充,并且由于此初始 null 值,它会导致某些组件的渲染不正确。

这是我的身份验证钩子:

export function useAuthentication() {
   const firebase = getFirebase();
   // this token is just additional token from my backend (not related to firebase)
   const token = localStorage.getItem('token') || null;
   const [loggedIn, setLoggedIn] = useState(true);

   useEffect(() => {
      firebase.auth().onAuthStateChanged(async (user) => {
         if (!user && !token) {
            setLoggedIn(false);
         } else {
            setLoggedIn(true);
         }
      });
   }, [firebase, token]);

   return { loggedIn };
}

如何改进/添加对已验证状态的更好处理?

【问题讨论】:

    标签: reactjs firebase authentication redux


    【解决方案1】:

    因为身份验证是客户端,您只需要处理最初不知道身份验证状态的问题(或将您的身份验证移至服务器)。您可以将初始 isLoggedIn 状态设置为 null 并在代码中处理该状态,直到 isLoggedIn 设置为 true/false。

    export function useAuthentication() {
       const firebase = getFirebase();
       // this token is just additional token from my backend (not related to firebase)
       const token = localStorage.getItem('token') || null;
       const [loggedIn, setLoggedIn] = useState(null);
    
       useEffect(() => {
          firebase.auth().onAuthStateChanged(async (user) => {
             if (!user && !token) {
                setLoggedIn(false);
             } else {
                setLoggedIn(true);
             }
          });
       }, [firebase, token]);
    
       return { loggedIn };
    }
    

    现在在你的代码中,你可以使用这个:

    export function MyPageComponent() {
      const { isLoggedIn } = useAuthentication()
    
      if (isLoggedIn === null) {
        // Show a loading screen here because you don't have the
        // authentication state so you don't know if the user is
        // logged in or not
        return (<p>Loading</p>)
      }
      // Now `isLoggedIn` will be true/false and you can handle the
      // state properly
      return (
        <MyPageWrapper isLoggedIn={isLoggedIn}>
          ...
        </MyPageWrapper>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 2016-04-07
      • 2017-12-09
      • 1970-01-01
      • 2020-07-13
      相关资源
      最近更新 更多