React Native - 检索除键之外的AsyncStorage中的所有内容?

时间:2018-01-16 17:58:45

标签: javascript json react-native foreach asyncstorage

目前,我正在使用 AsyncStorage.setItem()将带有字符串化JSON对象的字符串键推送到AsyncStorage。即: enter image description here

当我使用getAllKeys()和multiGet()检索AsyncStorage中的所有内容时,我意识到我只想访问对象本身并且没有使用密钥。

对于我来说,只访问字符串化对象的最有效方法是什么?我当前的函数,其中元素表示键和值:

importData = () => {
  AsyncStorage.getAllKeys().then(keys => AsyncStorage.multiGet(keys)
    .then((result) => {
      result.map(req => req.forEach((element) => {
        this.setState({ favorites: JSON.parse(element) });
        console.log(this.state.favorites);
      }));
    }));
}

1 个答案:

答案 0 :(得分:0)

这应该为您获得除键之外的所有值。如果您的数据属于层次结构,则需要JSON.parse()

  getData = async () => {
    try {
      await AsyncStorage.getAllKeys().then(async keys => {
        await AsyncStorage.multiGet(keys).then(key => {
          key.forEach(data => {
            console.log(data[1]); //values
          });
        });
      });
    } catch (error) {
      Alert.alert("Couldn't load data", error);
    }
  };