如何从AsyncStorage获取多个密钥,然后将这些密钥添加到数组中?

时间:2018-11-06 20:09:48

标签: javascript reactjs react-native asyncstorage

我想从AsyncStorage获取多个密钥并将这些密钥添加到数组中。

AsyncStorage.multiGet(
 ['key1',
  'key2',
  'key3',
  'key4',
  'key5',]
).then(() => {

})

3 个答案:

答案 0 :(得分:1)

multiGet以回调函数作为第二个参数,并且该回调函数用数组[['key1', 'dataForKey1'], ['key2', 'dataForKey2'], ... ]

调用

您可以使用map创建一个仅包含与键关联的数据的新数组。

AsyncStorage.multiGet(["key1", "key2", "key3", "key4", "key5"], function(stores) {
  const dataWithoutKeys = stores.map(entry => entry[1]);
});

答案 1 :(得分:0)

您可以为此使用地图功能:

AsyncStorage.getAllKeys((err, keys) => {
  AsyncStorage.multiGet(keys, (err, stores) => {
    stores.map((result, i, store) => {
      // get at each store's key/value so you can work with it
      let key = store[i][0];
      let value = store[i][1];
    });
  });
});

这是文档AsyncStorage

中的示例

答案 2 :(得分:0)

async getKeysData(keys){
  const stores = await AsyncStorage.multiGet(keys);
  return stores.map(([key, value]) => ({[key]: value}))
}

getKeysData(['key1', 'key2', 'key3'])
 .then((response)=>{ console.log(response)})
 
 /*
 Respose will be in below form 
 response = [
  {key1: 'DATAOF key1'},
  {key2: {"DATA OF KEY2"}}
  {key3: 'DATAOF key1'}
*/