【问题标题】:React.js Read User Info from AWS and set variable stateReact.js 从 AWS 读取用户信息并设置变量状态
【发布时间】:2020-02-29 22:21:40
【问题描述】:

如果自定义属性等于 1,我想读取用户信息并将“Admin”变量设置为 yes。 问题是,当我想读取用户属性时,程序会因 TypeError 崩溃:无法读取未定义的属性“属性”

这是我的代码:

import React, { useState, useEffect } from "react";
import './App.css';
import { Link, withRouter } from "react-router-dom";
import { Nav, Navbar, NavItem, Image } from "react-bootstrap";
import { LinkContainer } from "react-router-bootstrap";
import Routes from "./Routes";
import { Auth } from "aws-amplify";
import logo from './img/download.svg';


function App(props) {
    const [isAuthenticating, setIsAuthenticating] = useState(true);
    const [isAuthenticated, userHasAuthenticated] = useState(false);
    const [userData, setUserData] = useState([]);
    const [isAdmin, setIsAdmin] = useState(true);

    useEffect(() => {
      onLoad();
    }, [],);

    async function handleLogout() {
      await Auth.signOut();
      userHasAuthenticated(false);
      setIsAdmin(false);
      props.history.push("/login");
    }

    async function onLoad() {
      try {
        await Auth.currentSession();
        userHasAuthenticated(true);
        await Auth.currentUserInfo().then(user => setUserData(user));
        if (userData.attributes['custom:isAdmin'] === "1" ) {
          setIsAdmin(true)
        }
      }
      catch(e) {
        if (e !== 'No current user') {
        alert(e);
      }
    }

    setIsAuthenticating(false);
  }

return (...)

【问题讨论】:

    标签: javascript reactjs amazon-web-services amazon-cognito


    【解决方案1】:

    您好,在await 函数中,您似乎在then 内部设置userData 的值,但在外部您正在访问userData.attributes

    因此,也许当您检查 userData.attributes 时,userData 尚未填充,因为它是 asyncronous,而不是将其设置在 then 内,您可以使用 await 将响应分配为新变量,所以当async代码被执行时,它只会执行下一个代码。

    const user = await Auth.currentUserInfo();
    
    if(user.attributes['custom:isAdmin'] === "1" ) {
      setUserData(user);
      setIsAdmin(true);
    }
    

    【讨论】:

    • 非常感谢。这是我的问题的答案。
    【解决方案2】:

    我猜这是因为 setUserData() [基本上 setState()] 是一个异步函数,并且 if 块在您的状态设置(更新)之前执行。

    尝试使用 setTimeout()。

    await Auth.currentUserInfo().then(user => setUserData(user));
        setTimeout(()=>{
           if(userData.attributes['custom:isAdmin'] === "1" ) {setIsAdmin(true)}
         },0)
    

    【讨论】:

    • 您好,谢谢您的回答。可悲的是,这个解决方案似乎都不起作用,与 setTimeout 延迟相同的错误。我不知道为什么会这样,因为我在另一个组件中有相同的指令,并且 userData.attributes 被正确读取。
    猜你喜欢
    • 2020-09-12
    • 2017-11-29
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2021-02-01
    • 2017-09-19
    • 1970-01-01
    • 2013-04-05
    相关资源
    最近更新 更多