React中AWS Cognito返回对象无法存储:useState状态为空问题
问题:React useState无法保存AWS Cognito返回的用户属性状态
尝试渲染AWS Cognito返回的用户数据,但使用React的useState Hook存储时,attributes对象始终为空,最后一行的console.log(attributes)输出为空对象。
Cognito返回的用户数据对象:
{ "custom:type": "Donor", "sub": "48b8b2dd-7a7c-4cbf-b14e-cf70e55a9cd8", "address": "address1", "email_verified": false, "custom:abn": "12345678", "phone_number_verified": false, "given_name": "John", "custom:business_name": "Name of Business", "phone_number": "+1123456", "family_name": "Smith", "email": "test@gmail.com" }
我的React代码:
const [attributes, setAttributes] = useState({}); useEffect(() => { fetchAttributes(); }, []); const fetchAttributes = async() => { try{ const userData = await Auth.currentAuthenticatedUser(); const attributesList = userData.attributes; console.log(attributesList); setAttributes(attributesList); } catch (error) { console.log('error in fetching user data', error); } }; console.log(attributes);
解决方案:
1. 明确React状态更新的异步特性
setAttributes是异步操作,调用后不会立即修改attributes状态。组件首次渲染时,attributes是初始的空对象,此时执行的console.log(attributes)输出的就是初始值。当fetchAttributes异步完成并调用setAttributes后,组件会重新渲染,此时attributes才会持有Cognito返回的数据,但之前的console.log不会再次执行。
2. 验证状态是否正确更新
- 直接在JSX中渲染
attributes:<pre>{JSON.stringify(attributes, null, 2)}</pre> - 用
useEffect监听attributes的变化,在状态更新后打印:useEffect(() => { console.log("更新后的用户属性:", attributes); }, [attributes]);
3. 确保传入状态的是普通可枚举对象
如果userData.attributes是Cognito返回的特殊对象(比如不可枚举的属性容器),可以将其转换为普通对象后再设置状态:
// 使用扩展运算符创建新对象 setAttributes({ ...attributesList }); // 或者用Object.assign setAttributes(Object.assign({}, attributesList));
这样能确保React检测到状态引用的变化,触发组件重新渲染并更新状态。
内容的提问来源于stack exchange,提问作者Bsubs02
相关产品推荐
相关产品推荐

