我正在使用AsyncStorage来存储数据。这是我存储数据的功能:
const profile = { userId, name, email };
await AsyncStorage.setItem('userProf', JSON.stringify(profile));
如果我控制台,则尝试访问数据时遇到问题.log:
async componentWillMount(){
const profile = await AsyncStorage.getItem('userProf');
console.log(profile);
}
{"userId":"jefla3E0tjcJHhHKJK45QoIinB2","name":"egfgege","email":"ergeg@egrge.com"}
现在,如果我愿意只获得电子邮件值,我已经尝试过:
控制台.log(profile.email);
console.log(profile[0].email);
它们都不起作用,我未定义为输出,请您帮忙。
当 AsyncStorage 获取并返回一个字符串时,您需要将该字符串解析为 json。您已经在使用 JSON.stringify
来保存对象,您需要执行反向操作以使其恢复为对象。
const savedProfile = await AsyncStorage.getItem('userProf');
const profile = JSON.parse(savedProfile);
然后,您应该能够像往常一样访问它的属性,例如
const userId = profile.userId;
const email = profile.email;
const name = profile.name;
您可能需要确保执行检查 AsyncStorage 返回的值是否为 null,因为这会给您带来问题。此外,await
函数可能会引发,因此应确保将对 AsyncStorage 的调用包装在try/catch
async componentWillMount(){
try {
const savedProfile = await AsyncStorage.getItem('userProf');
// you should check that the savedProfile is not null here
const profile = JSON.parse(savedProfile);
const userId = profile.userId;
const email = profile.email;
const name = profile.name;
} catch (err) {
console.warn(err);
}
console.log(profile);
}
AsyncStorage.setItem( ... )
存储值时,使用 JSON.stringify
将完整的对象转换为String
。这意味着,如果你想有一个"正常"的Object
回来(使用点运算符),你必须使用JSON.parse
:
const profile = await AsyncStorage.getItem('userProf');
console.log(JSON.parse(profile));