【问题标题】:Adding API response data to previous AsyncStorage data in React Native在 React Native 中将 API 响应数据添加到之前的 AsyncStorage 数据中
【发布时间】:2021-06-25 17:37:58
【问题描述】:

我正在开发一个 React Native 应用程序,我在其中将 API 响应数据添加到 AsyncStorage。我正在发送多个 API 请求,并且需要将每个响应添加到以前存储的 AsynStorage 数据中。我试过 AsyncStorage.mergeItem('key',JSON.stringify(data)) 。但这只是将所有数据添加到一个对象。我希望单独添加每个对象。

这是我的示例 API 响应:

{data: [{type: "noun",
definition: "a domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, non-retractile claws, and a barking, howling, or whining voice.",
example: "she went for long walks with her dog"
}]
}

现在,我将其保存到 AsyncStorage,如下所示:

var data = response.data
await AsyncStorage.setItem('favourites', JSON.stringify(data));

最后,如果我有不同的响应,我想将其添加到以前的数据中,如下所示:

 [ {type: "noun",
    definition: "a domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, non-retractile claws, and a barking, howling, or whining voice.",
    example: "she went for long walks with her dog"
    },
  {type: "noun",
    definition: "a domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, non-retractile claws, and a barking, howling, or whining voice.",
    example: "she went for long walks with her dog"
    }
 ]

我该怎么做?

【问题讨论】:

    标签: javascript react-native asyncstorage


    【解决方案1】:

    你可以试试这个代码

    var data = response.data
    AsyncStorage.getItem('favourites')
    .then((favourites) => {
          const prevData = JSON.parse(favourites);
          const newData = favourites ? [...prevData,...data] : [];
          AsyncStorage.setItem('favourites', JSON.stringify(newData));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 2018-06-20
      • 2022-11-24
      相关资源
      最近更新 更多