reactjs - 为什么在使用 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>
);
}
解决方案
推荐阅读
- javascript - 获取另一个域上页面的内容
- vba - 在 word 中导入宏 - Visual Basic 错误
- php - 如何在本地计算机上安装的服务器上编写程序包?
- java - 无法加载请求的类:Tomcat 和 IntelliJ 上的 com.mysql.jdbc.Driver
- javascript - 从单独的 JavaScript 文件禁用另一个 HTML 文件上的按钮
- javascript - 在 Angular 中使用 jQuery 是一种不好的做法吗?
- angularjs - 无法在我的控制器 AngularjS 中访问表单内容,例如用户名...
- php - 中间字符串 RegEx/PHP 空格删除“在其他地方”工作
- reactjs - 如何使用 Jest 和 Enzyme 测试按钮的 onClick 道具
- django - AttributeError:“ModelFormOptions”对象没有属性“private_fields”