Reactjs 在React中将异步函数放入useffect()钩子

Reactjs 在React中将异步函数放入useffect()钩子,reactjs,Reactjs,我正在完成一个应用程序,我想把我的谷歌地图API密钥隐藏在我的安全API后面。我的目的是在验证我是否有经过身份验证的用户后调用API密钥。问题是,在异步调用之间,状态更改不会反映更改 这就是我正在做的: export default function App() { const [dateRange, setDateRange] = useState(initialDateRange); const [formState, updateFormState] = useState(init

我正在完成一个应用程序,我想把我的谷歌地图API密钥隐藏在我的安全API后面。我的目的是在验证我是否有经过身份验证的用户后调用API密钥。问题是,在异步调用之间,状态更改不会反映更改

这就是我正在做的:

export default function App() {
  const [dateRange, setDateRange] = useState(initialDateRange);
  const [formState, updateFormState] = useState(initialFormState);
  const [user, setUser] = useState(null);
  const [googleApiKey, setGoogleApiKey] = useState(null);

  useEffect(() => {
    async function updateAuth() {
      try {
        await checkUser();
        await getGoogleApiKey();
        await setAuthListener();
      } catch (error) {}
    }
    updateAuth();
  }, []);

  async function checkUser() {
    try {
      const user = await Auth.currentAuthenticatedUser();
      setUser(user);
      if (user !== authenticatedUser) {
        updateFormState(() => ({
          ...formState,
          authenticatedUser: user
        }));
      }
    } catch (error) {
      console.log(error);
    }
  }

  async function getGoogleApiKey() {
    const googleApiUrl = `${process.env.REACT_APP_API_PATH}apikey?googleapikey=true`; 
    try {
      console.log('USER_USER_USER', user);
      const apiKey = await fetch(googleApiUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: user.signInUserSession.idToken.jwtToken
        }
      });
      console.log('GOT_GOOGLE_API_KEY', apiKey);
      setGoogleApiKey(apiKey);
    } catch (error) {
      console.log(error);
    }
  }

  async function setAuthListener() {
    Hub.listen('auth', (data) => {
      const event = data.payload.event;
      switch (data.payload.event) {
        case 'signOut':
          console.log('signing out...');
          console.log(event);
          updateFormState(() => ({
            ...formState,
            username: '',
            password: '',
            email: '',
            authenticatedUser: null
          }));
          break;
        default:
          break;
      }
    });
  }
但我得到了一个错误:

USER_USER_USER null
App.js:78 TypeError: Cannot read property 'signInUserSession' of null
    at getGoogleApiKey (App.js:72)
    at updateAuth (App.js:42)

如果这是一个错误的范例,我将感谢任何替代方案

调用
setUser
时,
user
变量仍然保存旧的
user
信息(
null
,在这种情况下),而不管
async/await

等待checkUser();//setUser(某些内容)在下次运行之前不会发生
等待GetGoogleAppKey();//用户仍然为空
等待setAuthListener();
另一种选择是在
用户更改时添加另一种效果:

useEffect(() => {
  if (user) {
     getGoogleApiKey();
  }
}, [user]);
或者,使用以下参数调用
getGoogleAppKey

const user = await checkUser(); // return user
await getGoogleApiKey(user);
await setAuthListener();

由于逻辑变得复杂,我建议尝试调度,因为调度简化了这种复杂的来回场景。

我使用了
const user=await checkUser();//返回用户
并且它工作正常。。。如果api键不为null,则向下按键到贴图组件并有条件地渲染它们。谢谢