我在React Native中工作,将js对象存储在异步存储中。
但我得到了以下错误,
有人能告诉我摆脱这个错误的方法吗。。。。?
代码
import AsyncStorage from '@react-native-async-storage/async-storage';
const data = [
{key:0, head:"Car Name :", value: "Ford Figo"},
{key:1, head:"Car Model :", value:"1.2 Titanium MT"},
{key:2, head:"Mfg Year :", value:"2009"},
{key:3, head:"Capacity :", value:"1198 cc"},
{key:4, head:"Fuel Type :", value:"Diesel"},
{key:5, head:"Car Plate :", value:"TM09EC8364"},
{key:6, head:"Chassis No :", value:"MCJGXYMTKIKM30798"},
{key:7, head:"Engine No :", value:"KM30798"}
];
const storeData = async (key,value) => {
try {
await AsyncStorage.setItem(key, JSON.stringify(value))
} catch (e) {
console.log('store err: '+e)
}
}
const getData = (key) => {
try {
const d = AsyncStorage.getItem(key)
return d != null ? JSON.parse(d) : null;
} catch(e) {
console.log('read err: '+e)
}
}
storeData('HomeData',data)
const Dat= getData('HomeData')
console.log(Dat)
输出
LOG read err: SyntaxError: JSON Parse error: Unexpected identifier "object"
LOG undefined
@windowsill指出,AsyncStorage API中的每个方法都返回一个promise对象。你需要等待它结束:
const getData = async key => {
try {
let d = await AsyncStorage.getItem(key);
d = d ? JSON.parse(d) : null;
return d;
} catch(e) {
console.warn(e)
}
}