【问题标题】:Firebase Auth user is logged out on every page refresh - ReactFirebase Auth 用户在每次页面刷新时注销 - React
【发布时间】:2022-01-17 23:57:42
【问题描述】:

每次刷新页面时,用户都会在身份验证后返回登录屏幕。我正在使用 onAuthStateChanged 侦听器,但是,在刷新页面后,它的行为就像没有经过身份验证的用户一样。

  const dispatch = useDispatch();
  const currentUser = useSelector((state) => state.user.value);
  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        dispatch(setCurrentUser({ email: user.email, uid: user.uid }));
        console.log("user", user.email);
      }
    });
  }, []);
  return currentUser.email ? <LoggedIn /> : <Welcome />;
}

【问题讨论】:

    标签: reactjs firebase react-redux firebase-authentication


    【解决方案1】:

    我知道onAuthStateChanges() 方法是异步的。因此,只需在此方法中移动重定向即可。

      const dispatch = useDispatch();
      const currentUser = useSelector((state) => state.user.value);
      useEffect(() => {
        auth.onAuthStateChanged((user) => {
          if (user) {
            dispatch(setCurrentUser({ email: user.email, uid: user.uid }));
            console.log("user", user.email);
            openRoute(<LoggedIn />)
            return
          }
          openRoute(<Welcome />)
        });
      }, []);
    }
    

    只要身份验证状态发生变化,此功能就会触发,因此如果您注销您想回到登录页面,这种方式将起作用。

    【讨论】:

      【解决方案2】:
        const dispatch = useDispatch();
        const currentUser = useSelector((state) => state.user.value);
        useEffect(() => {
          auth.onAuthStateChanged((user) => {
            if (user) {
              dispatch(setCurrentUser({ email: user.email, uid: user.uid }));
              console.log("user", user.email);
            }
          });
        }, [currentUser]);
        return currentUser?.email ? <LoggedIn /> : <Welcome />;
      }
      

      也许,这会有所帮助。 只需将 currentUser 添加到 useeffect 中的第二个参数数组中

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2016-05-09
      • 1970-01-01
      相关资源
      最近更新 更多