简体   繁体   English

React.js 从 AWS 读取用户信息并设置变量 state

[英]React.js Read User Info from AWS and set variable state

I would like to read user information and set “Admin” variable to yes if it's custom attributes is equal to 1. The problem is that when I want to read user attributes the program crashes with TypeError: Cannot read property 'attributes' of undefined"我想读取用户信息并将“Admin”变量设置为yes,如果它的自定义属性等于1。问题是当我想读取用户属性时,程序崩溃并出现TypeError:无法读取未定义的属性“属性”

This is my code:这是我的代码:

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 (...)

Hi It looks like in the await function you are setting the value of userData inside the then , but outside you are accessing userData.attributes .嗨,看起来在await function 中,您在then内部设置userData的值,但在外部您正在访问userData.attributes

So maybe when you are checking userData.attributes the userData hasn't been populated because it is asyncronous Instead of set it inside the then you can assign the response as a new variable using the await , so it will just excecute the next code when the async code has been excecuted.所以也许当你检查userData.attributes时 userData 没有被填充,因为它是asyncronous的而不是在里面设置它then你可以使用await将响应分配为一个新变量,所以它只会在执行下一个代码时执行async代码已被执行。

const user = await Auth.currentUserInfo();

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

I guess that is happening because setUserData() [basically setState()] is an asynchronous function and if block is executing before your state has been set (updated).我猜这是因为 setUserData() [基本上 setState()] 是一个异步 function 并且如果在您的 state 设置(更新)之前执行块。

Try using setTimeout().尝试使用 setTimeout()。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM