javascript - 挣扎着通过导航传递props,相信和我的AysncyStorage set multiple有关
问题描述
我正在尝试将一些值传递到另一个屏幕,当我第一次尝试使用一个值时它可以工作,使用async
单个项目的存储集,但是,现在我正在尝试多个并且每次我按下它都会崩溃我想从中获取数据的项目。
当我按下 FlatList 中的项目时存储数据
fetchOnPressOpacity = async item => {
this.state.totalCalories += item.food.nutrients.ENERC_KCAL;
this.state.totalFat += item.food.nutrients.FAT;
this.state.totalCarbs += item.food.nutrients.CHOCDF;
this.state.totalProtein += item.food.nutrients.PROCNT;
const firstPair = ["totalCalories", JSON.stringify(this.state.totalCalories)];
const secondPair = ["totalCarbs", JSON.stringify(this.state.totalCarbs)];
const thirdPair = ["totalProtein", JSON.stringify(this.state.totalProtein)];
const fourthPair = ["totalFat", JSON.stringify(this.state.totalFat)];
try {
this.setState({});
await AsyncStorage.multiSet(firstPair, secondPair, thirdPair, fourthPair);
} catch (error) {
console.log(error);
}
};
getData()
方法,我不太清楚如何存储数据:
getData = async () => {
try {
const values = await AsyncStorage.multiGet([
"totalCalories",
"totalCarbs",
"totalProtein",
"totalFat"
]);
} catch (e) {
// read error
}
console.log(values);
};
所以,现在我的主要问题是当我按下一个项目时应用程序崩溃。我收到以下错误,但不认为这是问题所在。
VirtualizedList:缺少项目的键,请确保在每个项目上指定键或 id 属性或提供自定义 keyExtractor。
我还可以在应用程序崩溃之前将值写入控制台。
你能告诉我吗?
解决方案
简单的解决方案
var items = [['key1', 'value1'], ['key2', 'value2']]
AsyncStorage.setItem("DATA_KEY", JSON.stringify(items))
// or
AsyncStorage.multiSet(items, () => {
//to do something
});
对于您的代码
var items = [firstPair, secondPair, thirdPair, fourthPair];
AsyncStorage.setItem("DATA_KEY", JSON.stringify(items))
获取数据
AsyncStorage.multiGet(["key1", "key2"]).then(response => {
//to do something
})
推荐阅读
- angular - 在现有元素上使用角度动画查询/交错?
- vb.net - 如何检测 Alt + Tab 键然后关闭表单?
- flow - 如何动态为组件充电?
- sql-server - 我确实在 sql 上选择并根据我想要在其中查找的内容创建新列,并添加另一列带有查找的答案
- vert.x - vertx Context 是在处理程序执行时新创建的还是在所有执行中共享处理程序?
- python - Django和mysql的集成
- saml-2.0 - SAML 2.0 身份验证上下文在以下场景中如何工作?
- routes - 如何在路由中建立连接
- sql - 将时间存储为数字。格式问题 - 00 为秒
- sql - MSSQL 中存储过程的刷新问题