Ionic 4中受身份验证保护的路由

时间:2020-03-21 19:33:30

标签: reactjs firebase firebase-authentication react-router

你好,我有React + Firebase + Ionic4。一旦未经身份验证的用户尝试使用离子标签链接访问/login,它应该呈现/account路由。只有当我第一次导航到/account时,我的代码才能工作。在其他标签之间切换后,我可以输入/account。谢谢。

根组件App.tsx

<IonApp>
    <IonReactRouter>
    <IonTabs>
        <IonRouterOutlet>
          <Route component={Account} path={ACCOUNT} exact={true} />
          <Route path={SIGN_IN} component={SignIn} exact={true} />
          <Route path={EVENTS} component={Events} exact={true} />
        </IonRouterOutlet>
        <IonTabBar slot="bottom">
          <IonTabButton tab="events" href={EVENTS}>
            <IonIcon icon={dateRangeIcon} />
            <IonLabel>Events</IonLabel>
          </IonTabButton>
          <IonTabButton tab="account" href={ACCOUNT}>
            <IonIcon icon={accountBoxIcon} />
            <IonLabel>My account</IonLabel>
          </IonTabButton>
        </IonTabBar>
      </IonTabs>
    </IonReactRouter>
  </IonApp>

在这里我检查Account.tsx是否通过了用户验证

useEffect(() => {
    console.log('Auth user object in Account useEffect', auth.user)
    const { db } = props.firebase
    if (auth.user) {
      const unsubscribe = db
        .collection('events')
        .get()
        .then((querySnapshot: any) => {
          const events: any = []
          querySnapshot.docs.forEach((doc: any) => {
            const data = doc.data()
            data.docId = doc.id
            console.log('firebase data', data)
            events.push(data)
          })
          setDataFetched(true)
        })
        .catch((error: any) => {
          return console.log('Error with fetching events', error)
        })
      return () => unsubscribe()
    } else {
      return props.history.push('/login')
    }
  }, [])

验证挂钩useAuth.tsx

const AuthContext = React.createContext(null)

export function AuthProvider({ children }: any) {
  const auth = useProvideAuth()

  return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>
}

const useAuth = () => useContext(AuthContext)

function useProvideAuth() {
  const [user, setUser] = useState(null)

  useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged(user => {
      if (user) {
        setUser(user)
      } else {
        setUser(false)
      }
    })

    return () => unsubscribe()
  }, [])

  return {
    user,
    loginWithFacebook,
    loginWithGoogle,
    signout,
  }
}
export default useAuth

0 个答案:

没有答案