在异步函数中反应useEffect

时间:2020-10-20 20:00:46

标签: reactjs

在反应导航中(我也可以在App.ts中这样做),我像这样触发认证:

export default function Navigation() {
  authenticateUser();
  ...
}

export default function authenticateUser() {
  const setLoadingUser = useStore((state) => state.setLoadingUser);

  firebase.auth().onAuthStateChanged(async (authenticatedUser) => {
    console.log('AuthenticateUser', authenticatedUser);
    setLoadingUser(false);
    if (authenticatedUser) {
      useAuthenticate(authenticatedUser);
    } else {
      console.log('No user');
      setLoadingUser(false);
    }
  });

  ...
}

为了简单起见,我现在只打印用户:

import { useEffect } from 'react';

export const useAuthenticate = (authenticatedUser) => {
  useEffect(() => {
    console.log('authenticatedUser', authenticatedUser);
  }, [authenticatedUser]);

  return true;
};

我相信,因为我是在异步Firebase useAuthenticate函数中调用onAuthStateChanged,所以React会抛出[Unhandled promise rejection: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:]

我该如何处理?

1 个答案:

答案 0 :(得分:1)

这应该是:

export default function authenticateUser() {
  const {setAuthenticated} = useAuthenticate();
  const setLoadingUser = useStore((state) => state.setLoadingUser);

  firebase.auth().onAuthStateChanged(async (authenticatedUser) => {
    console.log('AuthenticateUser', authenticatedUser);
    setLoadingUser(false);
    if (authenticatedUser) {
      setAuthenticated(authenticatedUser);
    } else {
      console.log('No user');
      setLoadingUser(false);
    }
  });

  ...
}

import { useEffect, useState } from 'react';

export const useAuthenticate = () => {
  const [authenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    console.log('authenticatedUser', authenticated);
  }, [authenticated]);

  return {authenticated, setAuthenticated};
};