首页 > 解决方案 > 挣扎着通过导航传递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。

我还可以在应用程序崩溃之前将值写入控制台。

你能告诉我吗?

标签: javascriptnode.jsreactjsreact-nativeasynchronous

解决方案


简单的解决方案

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
})

推荐阅读