使用reactContext来响应路由器-firebase私有路由

时间:2020-09-16 12:35:25

标签: javascript reactjs firebase firebase-authentication react-router

我将此用户上下文和useEffect进行Firebase身份验证。整个应用都围绕着这个。

export const UserProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState()
  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      setCurrentUser(user)
    })
  }, [])

  return (
    <UserContext.Provider value={currentUser}>{children}</UserContext.Provider>
  )
}

在我的组件中,我检查用户是否已通过身份验证,如果没有通过路由器历史记录来重定向用户。

const history = useHistory()
const currentUser = useContext(UserContext)
  const handleRedirect = () => {
    return history.push('/login')
  }
  return (
    <>
      {currentUser ? (
        <div>
          <MiniDrawer></MiniDrawer>
          <Container maxWidth="md">
            <h1>
              Hello {currentUser.displayName}
            </h1>
            <Container>
              <h2>Team Activity</h2>
            </Container>
          </Container>
        </div>
      ) : (
        handleRedirect()
      )}
    </>

每当我重新加载页面并登录时,它都会首先执行 handleredirect 方法,然后它将进入此方法中指定的登录页面(大约半秒钟),然后呈现正确的组件(条件中的第一个)。怎么办呢?该应用似乎需要一段时间才能意识到用户是否存在。

1 个答案:

答案 0 :(得分:0)

useEffect(() => { 
    setTimeout(() => {

        fire.auth().onAuthStateChanged((user) => {
            this.setState( { stateChanged: true } )
        });

   }, 1000)
}, [])