如何在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
相关产品推荐
相关产品推荐

