gpt4 book ai didi

json - React Native - 返回 AsyncStorage 中的所有 JSON 数据?

转载 作者:行者123 更新时间:2023-12-03 13:58:03 24 4
gpt4 key购买 nike

在我的 React Native 应用程序的 AsyncStorage 中,我有多个 JSON 对象,每个对象都有一个唯一的 key ID,如下所示:

 '62834456':
data: { "foo": "bar",
"nicknames": [ "grizz", "example" ],
... and so on }

它们已被推送到 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!'));
}
}

在上述函数中console.logging 'json'时,结果为null。如何正确访问 AsyncStorage 中的所有 JSON 对象?

最终编辑

使用您的代码示例并删除 JSON.parse (因此只需 console.logging req)会返回以下内容: enter image description here

发生这种情况是因为由于某种原因 .forEach 返回数组中的第一个字符串,数组本身,然后是第二个字符串。

最佳答案

为了获取所有 AsyncStorage key ,您需要调用 AsyncStorage.getAllKeys()。为了加快速度,您还应该使用 AsyncStorage.multiGet() 通过这样做,您的代码将变为:

importData = async () => {
try {
const keys = await AsyncStorage.getAllKeys();
const result = await AsyncStorage.multiGet(keys);

return result.map(req => JSON.parse(req)).forEach(console.log);
} catch (error) {
console.error(error)
}
}

关于json - React Native - 返回 AsyncStorage 中的所有 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48194482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com