zah*_*nzy 2 json asynchronous reactjs react-native asyncstorage
在我的React Native应用程序的AsyncStorage中,我有多个JSON对象,每个对象都有一个唯一的键ID,如下所示:
'62834456':
data: { "foo": "bar",
"nicknames": [ "grizz", "example" ],
... and so on }
Run Code Online (Sandbox Code Playgroud)
它们已被推入字符串化的AsyncStorage中。我正在尝试通过其ID检索每个对象,并将ID及其JSON数据都推入组件的状态。到目前为止,我有:
// for every key in async storage, push to favorites in state
importData = (id) => {
for (id in AsyncStorage) {
return AsyncStorage.getItem(id)
.then(req => JSON.parse(req))
.then(json => console.log(json))
.catch(error => console.log('error!'));
}
}
Run Code Online (Sandbox Code Playgroud)
当在上述函数中使用console.logging'json'时,结果为null。如何正确访问AsyncStorage中的所有JSON对象?
最终编辑
使用您的代码示例并删除JSON.parse(因此只需console.logging req)将返回以下内容:
出现这种情况的原因是因为某种原因。forEach返回了数组中的第一个字符串,数组本身,然后是第二个字符串。
为了获取所有AsyncStorage密钥,您需要调用AsyncStorage.getAllKeys()
。为了加快速度,您还应该使用AsyncStorage.multiGet()
By来使代码成为;
importData = (id) => {
AsyncStorage.getAllKeys().then(async (keys) => {
const result = await AsyncStorage.multiGet(keys);
return result.map(req => JSON.parse(req)).forEach(console.log);
});
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这是使用 async/await 函数获取所有项目的更优雅的方法
const fetchAllItems = async () => {
try {
const keys = await AsyncStorage.getAllKeys()
const items = await AsyncStorage.multiGet(keys)
return items
} catch (error) {
console.log(error, "problemo")
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3823 次 |
最近记录: |