You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS Amplify React V6中获取并展示用户姓名与邮箱

AWS Amplify V6 React 展示用户信息完整示例

以下是适配AWS Amplify V6的React聊天应用示例代码,实现当前登录用户姓名、邮箱展示,以及实时更新的当前时间功能:

import React, { useState, useEffect } from 'react';
import { Auth, configure } from 'aws-amplify';

// 替换为你的AWS Amplify配置信息
configure({
  Auth: {
    region: '你的区域',
    userPoolId: '你的用户池ID',
    userPoolWebClientId: '你的客户端ID'
  }
});

function App() {
  const [userAttributes, setUserAttributes] = useState(null);
  const [loading, setLoading] = useState(true);
  const [currentTime, setCurrentTime] = useState(new Date());

  // 获取当前登录用户属性
  useEffect(() => {
    const fetchUserData = async () => {
      try {
        // 先确认用户已登录
        await Auth.currentAuthenticatedUser();
        // 获取用户属性
        const attributes = await Auth.fetchUserAttributes();
        // 转换为对象格式方便取值
        const attrObj = attributes.reduce((acc, attr) => {
          acc[attr.Name] = attr.Value;
          return acc;
        }, {});
        setUserAttributes(attrObj);
      } catch (err) {
        console.log('用户未登录或获取属性失败:', err);
        setUserAttributes(null);
      } finally {
        setLoading(false);
      }
    };

    fetchUserData();
  }, []);

  // 实时更新当前时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    // 组件卸载时清除定时器
    return () => clearInterval(timer);
  }, []);

  if (loading) {
    return <div>加载中...</div>;
  }

  return (
    <div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
      <h1>聊天应用</h1>
      {userAttributes ? (
        <div className="user-info">
          <h3>当前用户信息</h3>
          <p><strong>用户名:</strong> {userAttributes.name || userAttributes.username || '未设置'}</p>
          <p><strong>邮箱:</strong> {userAttributes.email}</p>
        </div>
      ) : (
        <p>请先登录以查看用户信息</p>
      )}
      <div className="current-time">
        <p><strong>当前时间:</strong> {currentTime.toLocaleString()}</p>
      </div>
    </div>
  );
}

export default App;

关键说明

  • 确保已安装依赖:执行 npm install aws-amplify
  • 必须先完成用户登录流程,fetchUserAttributes 仅对已登录用户生效
  • 时间更新通过 setInterval 实现,组件卸载时自动清除定时器,避免内存泄漏
  • 用户属性字段可能因你的用户池配置略有差异,可根据实际返回的属性键名调整(比如部分用户池用preferred_username替代name)

内容的提问来源于stack exchange,提问作者Tim Manns

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:32:41