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

如何在Amplify Gen 2中通过Authenticator获取用户注册属性?

解决Amplify Authenticator无法获取用户name、family_name属性的问题

Amplify的Authenticator组件返回的user对象默认只包含username、userId这类基础身份信息,你注册时收集的name、family_name属于用户自定义属性,需要主动调用接口拉取,具体操作如下:

  • 从Amplify Auth模块导入fetchUserAttributes方法
  • 用useState存储获取到的用户属性,通过useEffect在组件加载时异步拉取数据
  • 渲染页面时直接使用存储好的属性值

修改后的代码示例:

import { useState, useEffect } from 'react';
import { Authenticator } from '@aws-amplify/ui-react';
import { fetchUserAttributes } from '@aws-amplify/auth';
import '@aws-amplify/ui-react/styles.css';

export default function App() {
  const [userAttributes, setUserAttributes] = useState({});

  useEffect(() => {
    const getAttributes = async () => {
      try {
        const attributes = await fetchUserAttributes();
        setUserAttributes(attributes);
      } catch (err) {
        console.error('获取用户属性失败:', err);
      }
    };
    getAttributes();
  }, []);

  return (
    <Authenticator signUpAttributes={[
      'name', 
      'family_name', 
      'phone_number',
      ]}>
      {({ signOut, user }) => (
        <main>
          <h1>Hello {user?.username}</h1>
          <h1>姓名: {userAttributes.name} {userAttributes.family_name}</h1>
          <h1>{user?.signInDetails?.loginId}'s files</h1>
          <button onClick={signOut}>退出登录</button>
        </main>
      )}
    </Authenticator>
  );
}

额外注意事项:

  • 确保你的Cognito用户池已将name、family_name设置为可读取属性
  • fetchUserAttributes需要用户处于登录状态,Authenticator的上下文已确保这一点,可安全调用

内容的提问来源于stack exchange,提问作者jamal seder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:10:54