首页 > 解决方案 > 为什么在使用 Auth.currentAuthenticatedUser() 和 useEffect 时我的状态不会改变?

问题描述

我正在开发一个 AWS amplify 项目,我试图使用 amplify 提供的 useEffect 和 Auth 类来管理我的 App.js 状态。

所以我的目标是在用户进入应用程序时首先检查 Auth.currentAuthenticatedUser(),并更新我的状态 (isLogged userEmail),以便我能够将它传递给它的子组件,如 NavBar。

我尝试通过一些方法来做到这一点,比如在组件外部使用上下文/使用 initialState,但它没有奏效。

我可以记录数据,但是当我尝试更新我的状态时它不起作用。根据 Auth 用户处理这种状态的正确方法是什么?

import React, { useEffect, useState } from "react";
import Amplify, { Auth, Hub } from "aws-amplify";
import awsconfig from "./aws-exports";
import Layout from "./Layout";
import { AuthContext } from "./context/context";
Amplify.configure(awsconfig);

export default function App() {
  const [isLogged, updateIsLogged] = useState(false);
  const [userEmail, setUserEmail] = useState("");

  useEffect(() => {
    Auth.currentAuthenticatedUser().then((data) => {
      updateIsLogged(true);
      setUserEmail(data.attributes.email);
    });

    console.log("islogged : ", isLogged);
    console.log("email : ", userEmail);

    Hub.listen("auth", (data) => {
      const { payload } = data;
      console.log("new event has happend ", data);
      if (payload.event === "signIn") {
        updateIsLogged(true);
        setUserEmail(data.attributes.email);
        console.log("user has signed in");
      }
      if (payload.event === "signOut") {
        updateIsLogged(false);
        console.log("user has signed out");
      }
    });
  }, []);

  return (
    <Layout isLogged={isLogged} userEmail={userEmail}>
      {" "}
    </Layout>
  );
}

标签: reactjsreact-hooksamazon-cognitoaws-amplify

解决方案


推荐阅读